Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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").

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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(date);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading