Dario Chiga Dario Chiga - 6 days ago 6
Java Question

My SimpleDateFormat is always giving me a wrong result

Why does my SimpleDateFormatter always create a false output?
I send the Date in String-Format via Rest-service and receive it like this:
"11.28.2016 15:05:00"

And this is my Code where i try to parse it:

private static Date GetStartTimeString(String startTime) {
Date now = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss z");
try {
now = df.parse(startTime);
}
catch (ParseException e) {
e.printStackTrace();
}

return now;
}


The result i get is: "Mon Nov 28 18:02:05 GMT+00:00 2016"
The Date is right but the time is always wrong.

Answer

It's not that the parser is failing in the time part, is that the input doesn't match the pattern, the ParseException is being thrown and you are returning now as new Date(); Try with the code bellow.

    private static Date GetStartTimeString(String startTime) {
    Date now = new Date();
    DateFormat df = new SimpleDateFormat("MM.dd.yyyy HH:mm:ss");
    try {
        now = df.parse(startTime);
    }
    catch (ParseException e) {
        e.printStackTrace();
    }

    return now;
}

I strongly recommend you to deal with the exception in a way you break the natural flow (rethrowing the exception for example) so you don't get this kind of hard to debug kind of errors.

Comments