Question

I've a problem to convert a data in Java using Joda-Time library. Pratically, the input date have this format:

Mon Apr 28 18:57:42 CEST 2014

I would like to see this output:

2014-04-28

I've tried this code, but doesn't works:

    DateTimeFormatter dtf_out = DateTimeFormat.forPattern("yyyy-MM-dd");
    DateTimeFormatter dtf_inp = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss zzz yyyy");
    String a = String.valueOf(dtf_inp.parseDateTime(String.valueOf(resultsJs.get(0).getTimestamp()))); //crash here
    String b = String.valueOf(dtf_out.parseDateTime(a));

Note: resultsJs.get(0).getTimestamp() is a Date format.

Instead, this is the log:

...
Caused by: java.lang.IllegalArgumentException: Invalid format: "Mon Apr 28 18:57:42 CEST 2014"
            at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:873)
...
Was it helpful?

Solution

You are trying to parse an epoch millisecond value, but you can only parse a String.

However, it seems you already have a millisecond value available, so only the formatting is required, which is via the print() method:

DateTimeFormatter dtf_out = DateTimeFormat.forPattern("yyyy-MM-dd");
String b = dtf_out.print(resultsJs.get(0).getTimestamp().getTime());

OTHER TIPS

Its working fine after removing timezone info from the actual string but I have used time zone while parsing hence it will give you the correct result based on locale.

Please validate the result.

// pattern zzz is removed that is used for parsing time zone
DateTimeFormatter dtf_inp = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss yyyy");

// time zone is added while parsing date time
DateTime dateTime = dtf_inp.withZone(DateTimeZone.forID("Europe/Paris"))
                                   .parseDateTime("Mon Apr 28 18:57:42 2014");

// simply call toString(pattern) on DateTime
System.out.println(dateTime.toString("yyyy-MM-dd")); // 2014-04-28
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String output = sdf.format(yourDate);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top