I have a string "2020-03-25T22:00:00.000Z" which i want to convert to OffsetDateTime. Below is the code I tried but when I pass milisecond as 000 then it is not reflecting in OffsetDateTime.
OffsetDateTime offsetDateTime=OffsetDateTime.parse("2020-03-25T22:00:01.123Z",
DateTimeFormatter.ISO_OFFSET_DATE_TIME);
print(offsetDateTime)
//Output: 2020-03-25T22:00:01.123Z
But when mili is 000 then
OffsetDateTime offsetDateTime=OffsetDateTime.parse("2020-03-25T22:00:01.000Z",
DateTimeFormatter.ISO_OFFSET_DATE_TIME);
print(offsetDateTime)
//Output: 2020-03-25T22:01Z (mili second is missing)
I tried custom formattter also but it behave same
OffsetDateTime.parse("2020-03-25T22:00:00.123Z",
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX"));
Can anyone please help me out
You have to remember that the format you used to parse the ISO-String may not be the same format used for converting the date-time object back to a String.
When you print the offset date time like this:
System.out.println(odt);
Then the OffsetDateTime.toString() method will be called, and from its documentation:
Outputs this date-time as a String, such as 2007-12-03T10:15:30+01:00. The output will be one of the following ISO-8601 formats:
- uuuu-MM-dd'T'HH:mmXXXXX
- uuuu-MM-dd'T'HH:mm:ssXXXXX
- uuuu-MM-dd'T'HH:mm:ss.SSSXXXXX
- uuuu-MM-dd'T'HH:mm:ss.SSSSSSXXXXX
- uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSSXXXXX
The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.
Again, keep in mind that any class in the java.time package will not have a format, all those classes consist of some long fields which represent milliseconds or days etc.
I possibly can't stress this enough, but that is the essence when working with date and time: java.time classes do not have a format, you need to convert them into an appropriate format.
So if you always want to have the full value, then you simply need to format the OffsetDateTime to a String before you print it.
// best is to store that in a static variable
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
// parse using our custom formatter
OffsetDateTime odt = OffsetDateTime.parse("2020-03-25T22:00:00.000Z", dtf);
// print using our custom formatter
String formatted = odt.format(dtf);
System.out.println(formatted);
Which outputs:
2020-03-25T22:00:00.000Z
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With