Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java date parser off by two years

Tags:

java

date

I really don't know where to start debugging this one.

Code:

String date = "Mon, 15 Oct 2012 20:32:12 +0000 (GMT)";

        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:MM:ss Z");

        try {
            Date date2 = format.parse(date);
            System.err.println("parsed: " + date2);
        }
        catch (ParseException e) {
            System.err.println("Failed to parse: " + format);
        }

Output:

parsed: Fri Aug 15 16:00:12 EDT 2014

Why is this off by two years and two months?

like image 792
djechlin Avatar asked Aug 23 '26 10:08

djechlin


2 Answers

Use small mm for minutes

EEE, dd MMM yyyy HH:mm:ss Z
like image 112
jmj Avatar answered Aug 25 '26 23:08

jmj


Jigar Joshi has already answered the main question - but just a tip that setting DateFormat.setLenient(false) (see the JavaDoc) will avoid a lot of parsing problems like this, because the format won't silently accept nonsensical values.

A second tip (because this bit me recently) is to always test your DateFormats with both a.m. and p.m. timestamps, because it is easy to mix up hh and HH formats (12-hour and 24-hour format). Otherwise, you can find that your test data works fine, but real data fails with confusing errors.

like image 34
DNA Avatar answered Aug 26 '26 00:08

DNA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!