0

how to parse date format like "10/07/2018 10:07 pm" in Groovy.

Below format we are used

Date.parse("dd-MM-yyyy hh:MM:SS","10/07/2018 10:07 pm")

is it correct

tim_yates
  • 167,322
  • 27
  • 342
  • 338
Mohammed Shaheen MK
  • 1,199
  • 10
  • 10

3 Answers3

1

No, it should be

Date d = Date.parse("dd/MM/yyyy hh:mm aa","10/07/2018 10:07 pm")

​ Or if you're running on top of Java 8, you can use the much nicer

LocalDateTime d = LocalDateTime.parse(
    "10/07/2018 10:07 pm",
    DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm aa")
)
tim_yates
  • 167,322
  • 27
  • 342
  • 338
0

I'd recommend using Java 8 types instead of java.util.Date. Sadly, there's not a straightforward way to accommodate the lower case "pm" with DateTimeFormatter. The cheap way is to upper-case the String:

java.time.LocalDateTime.parse('10/07/2018 10:07 pm'.toUpperCase(), 'dd/MM/yyyy hh:mm a')

The more "proper" way, as described in this SO post, is:

import java.time.LocalDateTime
import java.time.format.*
import java.time.temporal.ChronoField

DateTimeFormatter dtf = new DateTimeFormatterBuilder()
        .appendPattern('dd/MM/yyyy hh:mm ')
        .appendText(ChronoField.AMPM_OF_DAY, [(0L):'am',(1L):'pm'])
        .toFormatter();
LocalDateTime.parse('10/07/2018 10:07 pm', dtf)
bdkosher
  • 5,753
  • 2
  • 33
  • 40
0

The format should be dd-MM-yyyy hh:MM:SS a

Date.parse("dd-MM-yyyy hh:MM:SS a","10-07-2018 10:07:00 am")
Date.parse("dd/MM/yyyy hh:MM a","10/07/2018 10:07 pm")

​Please check the results here: https://groovyconsole.appspot.com/script/5203535180333056

Ashu
  • 2,066
  • 3
  • 19
  • 33