1

I have searched online but couldn't really find the way to do it as I hope.

My data look like "20201005114527", "20201002173838" .......

and would like to convert them into LocalDateTime.

It will be converted into json again afterwards.

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "xxx/xxx") 
private LocalDateTime xxxxxDate;

But I'm just confused of converting those "number-only strings" into LocalDateTime.

Tsao
  • 139
  • 1
  • 10
  • 1
    Do you just want to convert the string **20201005114527** to an instance of `LocalDateTime`? – Abra Oct 05 '20 at 07:32
  • 1
    Unless you are using the time for "Booking appointments", use ZonedDateTime ot Instant instead for regular buisness apps for storing a record. More explaination can be found here. see answer with 900+ upvotes: https://stackoverflow.com/questions/32437550/whats-the-difference-between-instant-and-localdatetime – DigitShifter Oct 05 '20 at 07:44
  • Like in [this answer](https://stackoverflow.com/a/58770498/5772882). – Ole V.V. Oct 05 '20 at 09:04

2 Answers2

2

Use the format mask yyyyMMddHHmmss?

@JsonFormat(pattern = "yyyyMMddHHmmss")
private LocalDateTime xxxxxDate;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • That part is done by my co-worker and can't be changed.. – Tsao Oct 05 '20 at 07:01
  • 1
    I don't see any other obvious workaround here. If the format of some of the data doesn't match the current mask in the annotation, then the mask needs to change. – Tim Biegeleisen Oct 05 '20 at 07:02
0

Parsing a date-time string containing only digits isn’t any different from parsing a date-time string in any other format.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss");
    String numberOnlyString = "20201005114527";
    LocalDateTime xxxxxDate = LocalDateTime.parse(numberOnlyString, formatter);
    System.out.println(xxxxxDate);

Output:

2020-10-05T11:45:27

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161