java.time
Edit:
I tend to understand that you want to format today’s date into your format for comparison with other date-time strings in UTC (GMT) in the same format. For comparing dates and times I suggest that you compare date-time objects, not strings. So the options are two:
- Parse the existing string, convert it to a date in your time zone and compare it to today’s date.
- Parse your existing string into a point in time. Compare to the start of today’s date.
Let’s see both options in code.
1. Convert to date and compare dates:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss.SSSX");
ZoneId zone = ZoneId.systemDefault();
LocalDate today = LocalDate.now(zone);
String gmtString = "20201001220000.000Z";
LocalDate dateFromGmtString = formatter.parse(gmtString, Instant::from)
.atZone(zone)
.toLocalDate();
if (dateFromGmtString.isAfter(today)) {
System.out.println(gmtString + " is in the future");
} else if (dateFromGmtString.isBefore(today)) {
System.out.println(gmtString + " was on a past date");
} else {
System.out.println(gmtString + " is today");
}
Output:
20201001220000.000Z was on a past date
2. Find start of today’s date and compare times
Instant startOfDay = LocalDate.now(zone).atStartOfDay(zone).toInstant();
String gmtString = "20201001220000.000Z";
Instant timeFromGmtString = formatter.parse(gmtString, Instant::from);
if (timeFromGmtString.isBefore(startOfDay)) {
System.out.println(gmtString + " was on a past date");
} else {
System.out.println(gmtString + " is today or later");
}
20201001220000.000Z was on a past date
Original answer
You may be after the following. I recommend that you use java.time
, the modern Java date and time API, for your date and time work.
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss.SSSX");
String gmtString = "20201001220000.000Z";
Instant instant = sourceFormatter.parse(gmtString, Instant::from);
LocalDate date = instant.atZone(ZoneId.systemDefault()).toLocalDate();
String dayString = date.format(DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(dayString);
When I run the code in Europe/Warsaw time zone, the output is:
20201002
So the date has been converted from October 1 GMT to October 2 in Poland.
Edit:
… How can I get midnight?
To get the start of the day (usually 00:00):
ZonedDateTime startOfDay = time.atZone(ZoneId.systemDefault())
.truncatedTo(ChronoUnit.DAYS);
System.out.println(startOfDay);
2020-10-02T00:00+02:00[Europe/Warsaw]
Link: Oracle tutorial: Date Time explaining how to use java.time.