SimpleDateFormat convert date incorrect return value when hour is 12 [duplicate]

时间秒杀一切 提交于 2020-07-04 04:20:41

问题


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;
    }
}

回答1:


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.




回答2:


That happens because you are using SimpleDateFormat which is by default lenient. If you turn leniency off by setting setLenient(false):

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ", Locale.getDefault());
dateFormat.setLenient(false);

You will get an exception saying:

java.text.ParseException: Unparseable date: "2017-07-19T13:43:42.000+0000"

The root cause here is that you are submitting 13 for hours which requires HH pattern instead of hh. Because of leniency your code silently fixes the date instead of throwing an exception.

H Hour in day (0-23)

h Hour in am/pm (1-12)



来源:https://stackoverflow.com/questions/51478974/simpledateformat-convert-date-incorrect-return-value-when-hour-is-12

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!