Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have more control on zone offset formatting at DateTimeFormatter [duplicate]

Currently we are using

DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX")

To format the time range to an external vendor for a range of data, for India, that formatter will give time like this:

2018-04-26T00:00:00.000+0530

However, my vendor say they cannot accept this format and it have to look like

2018-04-26T00:00:00.000+05:30

However, look like in DateTimeFormatter, whatever I choose Z/z/X/x, I don't get that format of offset. Just wonder is that a way to customize the offset to be HH:mm?

Or, I need to get the offset in second and work that our myself?

like image 524
carfield Avatar asked Apr 27 '18 10:04

carfield


People also ask

What is basic_ ISO_ date?

BASIC_ISO_DATE. The ISO date formatter that formats or parses a date without an offset, such as '20111203'. static DateTimeFormatter.

What is DateTimeFormatter?

The DateTimeFormatter class in Java is used for parsing dates in different formats. You can use this class to format date in a specified format or you can use the predefined instances of DateTimeFormatter class.

Is DateTimeFormatter thread safe?

Yes, it is: DateTimeFormat is thread-safe and immutable, and the formatters it returns are as well. Implementation Requirements: This class is immutable and thread-safe.


1 Answers

It is three x. Just tried with JavaRepl:

java.time.format.DateTimeFormatter
    .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSxxx")
    .withZone(java.time.ZoneId.systemDefault())
    .format(java.time.Instant.now())

Results in

java.lang.String res10 = "2018-04-27T11:06:50.648+00:00"

After some trial and error, I saw that this is also documented in the API documentation of DateTimeFormatter but it is not easy to find (buried in a lot of other text):

Three letters outputs the hour and minute, with a colon, such as '+01:30'

DateTimeFormatter API Documentation

like image 176
David Tanzer Avatar answered Oct 22 '22 09:10

David Tanzer