JAVA OffsetDateTime custom hundredth of a second
I am currently looking for a custom date format and I cannot get it.
I want to get "1997-07-16T19:20:30.45+01:00"
using the following code:
OffsetDateTime o = OffsetDateTime.now();
String l = o.format(DateTimeFormatter.ISO_DATE_TIME);
Result:
2017-03-28T16: 23: 57,489 + 02: 00
Very close, but I need to have hh:mm:ss.XX
, not hh:mm:ss.XXX
.
Do you know how to set up OffsetDateTime
? I cannot find any good examples.
source to share
Your answer matches almost . If you look at the DateTimeFormatter
javadoc , you can see that lower case s
matches seconds and upper case s
, up to a fraction of a second :
Symbol Meaning Presentation Examples
------ ------- ------------ -------
s second-of-minute number 55
S fraction-of-second fraction 978
So, in your template s
and are s
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));
Output:
2017-06-19T20: 34: 29.75-03: 00
PS: Note that the fraction of a second 75
is greater than 59
, which is the maximum value for the seconds (in your answer seems to be correct, because the fraction of a second 48
, which gives the impression that it worked).
Another detail is that the offset in my case is -03:00
due to my system default timezone. Anyway, just fix your template and it should work.
For those who have the same problem.
It seems that with a template:
String ISO_OFFSET_DATE_TIME_WITH_HUNDREDTH_OF_SECOND = "yyyy-MM-dd'T'HH:mm:SS.ssXXX";
DateTimeFormatter dateTimeFormatter =
DateTimeFormatter.ofPattern(ISO_OFFSET_DATE_TIME_WITH_HUNDREDTH_OF_SECOND);
String ll = o.format(dateTimeFormatter);
System.out.println(ll);
I have the desired output:
2017-03-28T16: 44: 48.30 + 02: 00
source to share