Home > Back-end >  How can I get a String with UTC time in Java 6?
How can I get a String with UTC time in Java 6?

Time:05-20

I'm trying to get the current time in a String with the UTC format: 2022-05-19T18:20:53.480Z. However, I have to use jdk 6 and I'm having trouble finding the way to do it. Does anybody know how to do it? Thanks!

CodePudding user response:

tl;dr

Generate text:

org.threeten.bp.Instant.now().toString()

Parse text:

org.threeten.bp.Instant.parse( "2022-05-19T18:20:53.480Z" )

Avoid legacy date-time classes

The legacy date-time classes found in Java 6 are terribly flawed. Avoid Date, Calendar, etc.

ThreeTen-Backport

Use only java.time classes found in Java 8 and later. For Java 6 and 7, add the ThreeTen-Backport library to your project. This brings you most of the java.time functionality in nearly the same API.

Your input string’s format complies with ISO 8601 standard. The standard formats are used by default in java.time when parsing/generating text. So no need to specify a formatting pattern.

The Z on the end in your input string indicates an offset of zero hours-minutes-seconds. A moment in UTC (an offset of zero) is represented by Instant class.

Instant instant = Instant.parse( "2022-05-19T18:20:53.480Z" ) ;

Of course, I should add the obligatory caution that Java 6 is long past end-of-life. Using Java 6 without a paid support program providing updates is risky business. I strongly recommend you move to an LTS version of Java: versions 8, 11, and 17.

  • Related