Reputation: 9
I have to compare 2 dates date 1 - "2024-06-18T10:08:39.1271797" date 2 - "2024-06-18T10:08:39.124669"
I have to test compare both dates in ready api and make sure they both are equal. I dont need the last seconds.1271797 from date 1 and .124669 from date 2.
I have tried lots of options but failed. Can anyone please help me to trim those fields in groovy script for this please.
Upvotes: 0
Views: 113
Reputation: 79435
java.time
In March 2014, Java 8 introduced the modern, java.time
date-time API which supplanted the error-prone legacy java.util
date-time API. Any new code should use the java.time
API*.
Since your date-time strings are in the default format used by LocalDateTime#parse
, you do not need to specify any DateTimeFormatter
explicitly.
Having parsed these strings into a LocalDateTime
, you can truncate them to the seconds.
Demo:
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
date1 = LocalDateTime.parse("2024-06-18T10:08:39.1271797")
.truncatedTo(ChronoUnit.SECONDS)
date2 = LocalDateTime.parse("2024-06-18T10:08:39.124669")
.truncatedTo(ChronoUnit.SECONDS)
println date1 == date2
Output:
true
Learn more about the modern Date-Time API from Trail: Date Time.
* If you are receiving an instance of java.util.Date
, convert it tojava.time.Instant
, using Date#toInstant
and derive other date-time classes of java.time
from it as per your requirement.
Upvotes: -1
Reputation: 1026
Assuming you have a standard install, or groovy-dateutil
module on your classpath:
def fmt = "yyyy-MM-dd'T'hh:mm:ss"
assert Date.parse(fmt, "2024-06-18T10:08:39.1271797")
== Date.parse(fmt, "2024-06-18T10:08:39.124669")
If you know the format will never change, you can just compare strings:
assert "2024-06-18T10:08:39.1271797".split(/\./)[0] ==
"2024-06-18T10:08:39.124669".split(/\./)[0]
Upvotes: 2