rspec/rules/S2718/java/rule.adoc

52 lines
1.7 KiB
Plaintext
Raw Normal View History

== 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.
2021-04-28 16:49:39 +02:00
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.
2021-04-28 16:49:39 +02:00
The `ZonedDateTime` class provides a `truncatedTo` method that allows truncating the date
in a significantly faster way than the `DateUtils` class from Commons Lang.
2021-04-28 16:49:39 +02:00
*Note* that this rule is automatically disabled when the project's `sonar.java.source` is lower than `8`.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
[source,java,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
public Date trunc(Date date) {
return DateUtils.truncate(date, Calendar.SECOND); // Noncompliant
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
[source,java,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
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[]