Search code examples
javatimestampsimpledateformat

SimpleDateFormat convert date incorrect return value when hour is 12


I have having an issue converting dates in a json file to a timestamp. When the hour = 12, the timestamp being returned is incorrect.

Java version 1.8.0_171

Using the code snippet below, I expect the output to be

2017-07-19 07:43:42.0

2017-07-18 08:43:42.0

2017-07-19 09:43:42.0

Instead, I get

2017-07-19 07:43:42.0

2017-07-18 20:43:42.0

2017-07-19 09:43:42.0

I have tried on 2 machines, and had a co-worker run it, same results Can anyone see what the issue is; I am probably staring at it

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;

public class TimestampTest {

    public static void main(String[] args) {

        String input = "2017-07-19T11:43:42.000+0000";
        System.out.println(stringToTimestamp(input));

        input = "2017-07-19T12:43:42.000+0000";
        System.out.println(stringToTimestamp(input));

        input = "2017-07-19T13:43:42.000+0000";
        System.out.println(stringToTimestamp(input));

    }

    private static Timestamp stringToTimestamp(String input) {
        try {   
            if(StringUtils.isBlank(input)) {
                return null;
            }
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ",
                Locale.getDefault());
            java.util.Date parsedDate = dateFormat.parse(input);
            Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
            return timestamp;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

Solution

  • Aside from the fact you shouldn't be using Date or SimpleDateFormat any more, your error is because you are using hh instead of HH

    h -> Hour in am/pm (1-12)

    H -> Hour in day (0-23)

    Consider using LocalDateTime in your case.