简体   繁体   中英

Remove time zone part from - ZonedDateTime : JAVA

I am converting milliseconds into ZonedDateTime

Long lEpochMilliSeconds = 1668415926445;
System.out.println(ZonedDateTime.ofInstant(Instant.ofEpochMilli(lEpochMilliSeconds),ZoneId.of("UTC"));

It gives output:

2022-10-28T12:59:34.939Z[UTC]

I don't want the time zone "[UTC]" part in my output. I need my out to be like this in ZonedDateTime format:

2022-10-28T12:59:34.939Z

I need the forma t in ZonedDateTime only not string , as I will be returning the value & use it somewhere else

I need the format in ZonedDateTime only not string

This is like saying "I need an int that knows it's in hex rather than decimal". There's just no such concept.

If you need to format the value in a particular way, you should apply that format where you do the formatting .

It's possible that what you should actually do is return an Instant instead of a ZonedDateTime . That will format the way you want by default, although it's still not "part of the object" - just the default format for all instants.

It's important to understand the difference between "the value being represented" (and the type you're using to represent that value) and "a string representation of that value". You should try use the semantically-appropriate type for what you're trying to represent (eg ZonedDateTime , Instant etc) for as much of the time as possible, only converting to and from string representations at system boundaries. Those system boundaries need to be aware of the expected textual representation, and perform the appropriate conversion, rather than expecting a particular string representation to travel with the value itself through the system.

It is giving me the desired output when I gave ZoneOffset as an argument instead of ZoneId.

ZonedDateTime.ofInstant(Instant.ofEpochMilli(lEpochMilliSeconds), ZoneOffset.UTC);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM