2

Hi I'm trying to parse a string with a date in scala. I tried it the following way:

    import java.time.format.DateTimeFormatter
   import java.time.LocalDateTime
    val date="20 October 2015"
    val formatter=DateTimeFormatter.ofPattern("dd MMMM yyyy")
    val dt=LocalDateTime.parse(ts,formatter)

But I get the follwing exception:

java.time.format.DateTimeParseException: Text '20 october 2015' could not be parsed at index 3
  at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
  at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
  at java.time.LocalDateTime.parse(LocalDateTime.java:492)
  ... 29 elided 

For parsing I used the Standard Java API's DateTimeFormatter and LocalDateTime

jojo_Berlin
  • 673
  • 1
  • 4
  • 19

2 Answers2

2

Use

val dt=LocalDate.parse(date,formatter)

instead of LocalDateTime since your date string doesn't contain any time information.

Harald Gliebe
  • 7,236
  • 3
  • 33
  • 38
  • Does not solve the Issue: scala> val dt=LocalDate.parse(ts,formatter) java.time.format.DateTimeParseException: Text '24 December 2016' could not be parsed at index 3 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) at java.time.LocalDate.parse(LocalDate.java:400) – jojo_Berlin Mar 13 '17 at 06:45
  • That's strange, '24 December 2016' works for me. Do you have a non english system language? Could you try to construct your formatter with a locale: val formatter=DateTimeFormatter.ofPattern("dd MMMM yyyy").withLocale(Locale.US) – Harald Gliebe Mar 13 '17 at 08:34
1

You are confusion about LocalDate with LocalDateTime, LocalDateTime is used with Year, Month, Day with Times, like:

println(LocalDateTime.now())
> 2017-03-13T15:11:42.559

and LocalDate is used with Year, Monthand Day without Time, like:

println(LocalDate.now())
> 2017-03-13

As your example, you should use: LocalDate to parse time text, like:

LocalDate.parse(date,formatter)
chengpohi
  • 14,064
  • 1
  • 24
  • 42