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
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
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")
)
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)
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