0

The below one works:

LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
LocalDateTime.now().plusDays(1).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)

but the below item does not work.

LocalDateTime.now().format(DateTimeFormatter.ofPattern("YYYY-MM-DDTHH:mm:ss"))
LocalDateTime.parse("2019-11-14T16:48:48.288", DateTimeFormatter.ofPattern("YYYY-MM-DDTHH:mm:ss"));

LocalDateTime.now() gives me date like 2019-11-13T17:12:47.494. I have tried parsing it and verified online a lot to fix but no luck can someone help me to understand why the parsing is throwing exception and how to fix this.

Dinesh Kumar
  • 1,469
  • 4
  • 27
  • 46
  • 2
    That InvocationTargetException is probably masking the real cause. If you run those two lines in isolation you should get: `java.lang.IllegalArgumentException: Unknown pattern letter: T` – dnault Nov 13 '19 at 22:41
  • What do you think `YYYY-MM-DDTHH:mm:ss` represents? Why? – Sotirios Delimanolis Nov 13 '19 at 22:50
  • Ya this is the error : java.lang.IllegalArgumentException: Unknown pattern letter: T i will update my Question. Thanks for update. – Dinesh Kumar Nov 13 '19 at 22:56
  • Possible duplicate of [Parsing string to date: Illegal pattern character 'T'.](https://stackoverflow.com/questions/26398657/parsing-string-to-date-illegal-pattern-character-t) – Ole V.V. Nov 14 '19 at 03:16
  • 1
    You don’t need a formatter in this particular case, just leave it out: `LocalDateTime.parse("2019-11-14T16:48:48.288")`. This is because your string is in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, and the classes of java.time parse this format as their default, without a formatter specified. – Ole V.V. Nov 14 '19 at 03:19
  • 1
    *LocalDateTime.now() gives me date like 2019-11-13T17:12:47.494. I have tried parsing it …* I don’t understand. You can parse a *string*. `LocalDateTime.now()` doesn’t give you a string, it gives you a `LocalDateTime`, so there is no point in parsing in, it doesn’t make sense to try. – Ole V.V. Nov 14 '19 at 03:23

1 Answers1

2

You need to add single quotes '' around any literals:

LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"));
LocalDateTime.parse("2019-11-14T16:48:48.288", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"));

Also:

  • Use yyyy for year.
  • Use dd for day-of-month, instead of DD which is for day-of-year.
  • Use SSS for second fractions.
  • See DateTimeFormatter Javadoc for more information.
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417