简体   繁体   中英

find ZonedDateTime is today, yesterday or else

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 */);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM