Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda Time, parse is not working

Tags:

java

jodatime

I have this code, and don't know why it's not working

String dateTime = "Sun, 18 Apr 2004 02:32:43";
// Format for input
org.joda.time.format.DateTimeFormatter dtf = DateTimeFormat.forPattern("EEE, dd MMM yyyy kk:mm:ss");
// Parsing the date
DateTime jodatime = dtf.parseDateTime(dateTime);
// Format for output
org.joda.time.format.DateTimeFormatter dtfOut = DateTimeFormat.forPattern("dd MMM yyyy kk:mm:ss");
// Printing the date

The error I get:

Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "Sun, 18 Apr 2004 02:32:43"
    at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:945)
    at com.jbd.WeirdCutEmails.test(WeirdCutEmails.java:69)
    at com.jbd.WeirdCutEmails.main(WeirdCutEmails.java:108)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
like image 398
dzefrej0 Avatar asked Feb 06 '23 16:02

dzefrej0


1 Answers

(credit to Tom for the suggestion)

This is most likely a Locale issue: if your default Locale does not recognise 'Sun' and 'Apr' then the DateTimeFormatter will throw an IllegalArgumentException.

You can get around this by using withLocale(Locale locale):

DateTimeFormat.forPattern("EEE, dd MMM yyyy kk:mm:ss")
    .withLocale(Locale.ENGLISH)

Illustration:

@Before
public void setUp() throws Exception {
    Locale.setDefault(new Locale("pt", "BR"));
}

@Test(expected = IllegalArgumentException.class)
public void testDefaultFormatterWontParseDifferentLocale() {
    //arrange
    DateTimeFormatter dtf = DateTimeFormat.forPattern("EEE, dd MMM yyyy kk:mm:ss");

    //act
    dtf.parseDateTime("Sun, 18 Apr 2004 02:32:43"); //won't parse as expecting a String in Portuguese Locale
}

@Test
public void testFormatterWithSuppliedLocale() {
    //arrange
    DateTimeFormatter dtf = DateTimeFormat
                                .forPattern("EEE, dd MMM yyyy kk:mm:ss")
                                .withLocale(Locale.ENGLISH);

    //act
    DateTime actualDateTime = dtf.parseDateTime("Sun, 18 Apr 2004 02:32:43");

    //assert
    Assert.assertEquals(new DateTime(2004,4,18,2,32,43), actualDateTime);
}

@After
public void tearDown() throws Exception {
    Locale.setDefault(new Locale("en","US"));
}
like image 169
David Rawson Avatar answered Feb 16 '23 02:02

David Rawson