I have a list of ZonedDateTime objects (Eg. 2023-01-01T20:40:01.001+05:30[Asia/Kolkata])
I need to write a method to get the below results.
if ZonedDateTime is today -> return "Today"
if ZonedDateTime is yesterday -> return "Yesterday"
else -> return ZonedDateTime in "yyyy-MM-dd" format -> (Eg. DateTimeFormatter.ofPattern("yyyy-MM-dd").format(zonedDateTime))
How can I calculate if ZonedDateTime is today, tomorrow or else? "Today" as seen in the same timezone as ZonedDateTime
object.
You don't actually need to work with ZonedDateTime
s for the most part. Just find out what day today is in the desired ZoneId
, and then work with LocalDate
s from that point onwards.
Check if toLocalDate()
is equal to today, or if it is equal to today minus one day.
public static String getRelativeDateString(ZonedDateTime zdt) {
var today = LocalDate.now(zdt.getZone());
var ld = zdt.toLocalDate();
if (ld.equals(today)) {
return "Today";
} else if (ld.equals(today.minusDays(1))) {
return "Yesterday";
} else {
return ld.format(DateTimeFormatter.ISO_LOCAL_DATE /* or another formatter */);
}
}