0

I am having an Instant object . I would like to get yyyy-MM-dd as a string. How can I achieve it?

Instant defaultTime = Instant.now().truncatedTo(ChronoUnit.SECONDS);
System.out.println(defaultTime); // print 2021-03-26T00:00:00Z

How can I get "2021-03-26"?

ernest_k
  • 44,416
  • 5
  • 53
  • 99
Starbucks Admin
  • 585
  • 1
  • 8
  • 21
  • 2
    What time zone are you looking for the date in? I would call `atZone(...).toLocalDate()` to get the `LocalDate`, at which point it's easy to format. – Jon Skeet Mar 26 '21 at 08:01

1 Answers1

3

I suggest to cast to a LocalDateTime and then use DateTimeFormatter like

LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
String result = ldt.format(DateTimeFormatter.ISO_LOCAL_DATE);

You can find formatter list here, or use your own pattern

Other ways

As @Holger said in the comments, DateTimeFormatter.ISO_LOCAL_DATE.withZone(ZoneOffset.UTC) produces a formatter that can directly format the Instant and can be shared and reused to format a lot of instants.

static final DateTimeFormatter INSTANT_FORMATTER
        = DateTimeFormatter.ISO_LOCAL_DATE.withZone(ZoneOffset.UTC);

Use like

    String result = INSTANT_FORMATTER .format(instant);

@Ole V.V. mentioned that converting to LocalDateTime as in my first snippet throws away the information about which point in time we had. We can keep that information with us when instead we convert to ZonedDateTime or OffsetDateTime. If you want to interpret the date in UTC (as in the previous examples), for example:

    String result = instant.atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ISO_LOCAL_DATE);

This makes it more explicit that the operation is dependent on the choice of UTC for interpretation.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
IQbrod
  • 2,060
  • 1
  • 6
  • 28
  • 5
    Or directly `String result = DateTimeFormatter.ISO_LOCAL_DATE.withZone(ZoneOffset.UTC) .format(instant);` without the `LocalDateTime` detour. – Holger Mar 26 '21 at 08:21
  • @Holger, nice one – IQbrod Mar 26 '21 at 08:48
  • @Holger Thanks for the alternative. My personal taste is for the more explicit application of time zone in the answer. I would also prefer `ZonedDateTime` over `LocalDateTime`. Or `OffsetDateTime` if UTC is desired. So `defaultTime.atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ISO_LOCAL_DATE)`. – Ole V.V. Mar 27 '21 at 07:50
  • 2
    @OleV.V. for a single use, it doesn't matter, but `DateTimeFormatter.ISO_LOCAL_DATE.withZone(ZoneOffset.UTC)` produces a formatter that can be shared and reused, to format a lot of instances. – Holger Mar 27 '21 at 11:32
  • @Holger I found that both your suggestion and mine deserved to be kept here, and in particular the pros and cons of each, so I have edited them into the answer. IQbrod, if you don’t like it. please revert my edit. – Ole V.V. Mar 28 '21 at 09:00