-1

I'm trying to format date in Java. I need this format:

2017-06-10T12:38:15.687+03:00

How correctly convert this from standard Date format which I have got in a String?

Tue Jun 18 00:00:00 MSK 2024
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • It’s unfortunate that you have got only the old-fashioned `Date` format. Have you got that as a `String` or as a `Date` object? In the first (and worst) case, parse and format. In the latter case use `yourOldfashionedDateObject.toInstant()` and perform further conversions from there. – Ole V.V. Oct 25 '22 at 13:48
  • If you have got a `Date` object: `yourOldfashionedDateObject.toInstant().atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)`. If you have only got a string: `ZonedDateTime.parse(yourString, DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss zzz yyyy", Locale.ROOT)).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)`. Result in both ccases: `2024-06-18T00:00:00+03:00`. The formatter will print fraction of second too if non-zero. – Ole V.V. Oct 25 '22 at 15:02
  • It is a good solution, but how to convert in iso8601 format futher? – Андрей Андрей Oct 26 '22 at 06:24
  • 1
  • Thanks for reverting. I’m sorry, I don’t understand “further”. `.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)` gives you ISO 8601. What are you still missing? – Ole V.V. Oct 26 '22 at 06:48
  • in the result i have string like 2024-06-18T00:00:00+03:00, but i need format like 2024-06-18T00:00:00.687+03:00 – Андрей Андрей Oct 26 '22 at 07:08
  • First, your original string hasn’t got any fraction of second, so there is nowhere that I can see you can get `.687` from. `DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX")` will give you three decimals after the decimal point, but in this case they will always be `.000`. – Ole V.V. Oct 26 '22 at 07:16

1 Answers1

-1

Using new calendar API in Java 8.

API Class             Default Format
+-----------------------------------+
LocalDate              2021-12-25
LocalTime                         12:30:30
LocalDateTime          2021-12-25T12:30:30
OffsetTime                        12:30:30+01:00
OffsetDateTime         2021-12-25T12:30:30+01:00
ZonedDateTime          2021-12-25T12:30:30+01:00 Europe/Paris
Year                   2021
YearMonth              2021-12
MonthDay                   -12-25
Instant                2021-12-25T12:30:30.274Z
Find Bugs
  • 125
  • 3
  • with ZonedDateTime ? but i dont know pattern my formatt. And have problem with Msk timeZone – Андрей Андрей Oct 25 '22 at 12:33
  • Read the description of this format class: ```DateTimeFormatter``` – Find Bugs Oct 25 '22 at 12:39
  • 1
    It’s a very good suggestion, but it doesn’t answer the question. And yes, @АндрейАндрей, `ZonedDateTime` is the right class to use. For the pattern see [the 2nd linked original question](https://stackoverflow.com/questions/62105691/datetimeparse-exception). – Ole V.V. Oct 25 '22 at 14:19