rspec/rules/S2718/java/rule.adoc

52 lines
1.7 KiB
Plaintext

== Why is this an issue?
The `ZonedDateTime` is an immutable representation of a date-time with a time-zone, introduced in Java 8.
This class stores all date and time fields, to a precision of nanoseconds,
and a time zone, with a zone offset used to handle ambiguous local date times.
Date truncation to a specific time unit means setting the values up to the specific time unit to zero
while keeping the values of the larger time units unchanged.
The `ZonedDateTime` class provides a `truncatedTo` method that allows truncating the date
in a significantly faster way than the `DateUtils` class from Commons Lang.
*Note* that this rule is automatically disabled when the project's `sonar.java.source` is lower than `8`.
=== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
public Date trunc(Date date) {
return DateUtils.truncate(date, Calendar.SECOND); // Noncompliant
}
----
=== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
public Date trunc(Date date) {
Instant instant = date.toInstant();
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
ZonedDateTime truncatedZonedDateTime = zonedDateTime.truncatedTo(ChronoUnit.SECONDS);
Instant truncatedInstant = truncatedZonedDateTime.toInstant();
return Date.from(truncatedInstant);
}
----
== Resources
* https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/time/ZonedDateTime.html#truncatedTo(java.time.temporal.TemporalUnit)[Oracle SDK 20 - ZonedDateTime#truncatedTo]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use "ZonedDateTime.truncatedTo" instead. [(sonar.java.source not set. Assuming 8 or greater.)]
endif::env-github,rspecator-view[]