Search code examples
javadatetime-formatutctime-format

How to get UTC time of my local time with "Z" at the end?


I want to get current time in java in UTC:

So, I'm in Vienna now, the current local time is 16:30:29, current offset to UTC is 2 hours and I want to get

2022-05-27T14:30:29.813Z

with this Z at the end (indicating "Zulu time").

with this

public static String getIsoUtcDate() {
    Instant inst = Instant.now();
    return inst.toString();
}

I get

2022-05-27T14:30:29.813923100Z

How to get rid of microseconds?

I tried with SimpleDateFormat also, but with this I'm unable to get Z at the end.


Solution

  • You can use a OffsetDateTime and set its offset to UTC. Then use a DateTimeFormatter to format it. Like this:

    public static String getIsoUtcDate() {
        OffsetDateTime nowUtc = OffsetDateTime.now()
            .withOffsetSameInstant(ZoneOffset.UTC);
    
        return DateTimeFormatter.ISO_DATE_TIME.format(nowUtc);
    }