I am currently looking for a custom format of date and I can't obtain it.
I want to obtain "1997-07-16T19:20:30.45+01:00" using the following code :
OffsetDateTime o = OffsetDateTime.now();
String l = o.format(DateTimeFormatter.ISO_DATE_TIME);
The result is:
2017-03-28T16:23:57.489+02:00
Very close, but I only need to have hh:mm:ss.XX, and not hh:mm:ss.XXX.
Do you know how to customize OffsetDateTime? I can't find good examples.
Your answer is almost correct. If you take a look at DateTimeFormatter javadoc, you'll see that the lowercase s corresponds to the seconds, and uppercase S, to the fraction of seconds:
Symbol Meaning Presentation Examples
------ ------- ------------ -------
s second-of-minute number 55
S fraction-of-second fraction 978
So, in your pattern, s and S are inverted. The correct pattern is:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSXXX");
OffsetDateTime o = OffsetDateTime.now();
System.out.println(o.format(formatter));
The output is:
2017-06-19T20:34:29.75-03:00
PS: Note that the fraction of second is 75 - greater than 59, which is the maximum value for seconds (In your answer, it seems correct because the fraction of second is 48, which gives the impression that it worked).
Another detail is that the offset in my case is -03:00 because of my system's default timezone. Anyway, just fix your pattern and it should work.
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