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

Time:05-28

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.

CodePudding user response:

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

CodePudding user response:

Instant#truncatedTo

The Answer by marstran is more flexible. But for your particular case, there is a simpler way.

String output = 
    Instant
    .now()
    .truncatedTo( ChronoUnit.MILLIS )
    .toString() 
;
  • Related