当小时为 12 时,SimpleDateFormat 转换日期错误返回值 [英] SimpleDateFormat convert date incorrect return value when hour is 12

查看:33
本文介绍了当小时为 12 时,SimpleDateFormat 转换日期错误返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将 json 文件中的日期转换为时间戳时遇到问题.当小时 = 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 版本 1.8.0_171

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-19 07:43:42.0

2017-07-18 08:43:42.0

2017-07-18 08:43:42.0

2017-07-19 09:43:42.0

2017-07-19 09:43:42.0

相反,我得到

2017-07-19 07:43:42.0

2017-07-19 07:43:42.0

2017-07-18 20:43:42.0

2017-07-18 20:43:42.0

2017-07-19 09:43:42.0

2017-07-19 09:43:42.0

我在 2 台机器上尝试过,并让同事运行它,结果相同任何人都可以看到问题是什么?我可能正在盯着它

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

推荐答案

除此之外,您不应该使用 DateSimpleDateFormat ,您的错误是因为您使用的是 hh 而不是 HH

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 ->上午/下午的小时 (1-12)

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

H ->一天中的小时 (0-23)

H -> Hour in day (0-23)

考虑使用 LocalDateTime案例.

这篇关于当小时为 12 时,SimpleDateFormat 转换日期错误返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆