【问题标题】:SimpleDateFormat convert date incorrect return value when hour is 12 [duplicate]当小时为 12 时,SimpleDateFormat 转换日期不正确的返回值 [重复]
【发布时间】:2018-12-30 21:59:35
【问题描述】:

我在将 json 文件中的日期转换为时间戳时遇到问题。当小时 = 12 时,返回的时间戳不正确。

Java 版本 1.8.0_171

使用下面的代码 sn-p,我希望输出是

2017-07-19 07:43:42.0

2017-07-18 08:43:42.0

2017-07-19 09:43:42.0

相反,我得到了

2017-07-19 07:43:42.0

2017-07-18 20:43:42.0

2017-07-19 09:43:42.0

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

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

【问题讨论】:

标签: java timestamp simpledateformat


【解决方案1】:

发生这种情况是因为您使用的是默认宽松的SimpleDateFormat。如果您通过设置setLenient(false) 关闭宽大处理:

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

你会得到一个异常说:

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

这里的根本原因是您提交了几个小时的13,这需要HH 模式而不是hh。由于宽大处理,您的代码会默默地修复日期,而不是抛出异常。

一天中的小时 (0-23)

上午/下午的小时 (1-12)

【讨论】:

    【解决方案2】:

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

    h -> 上午/下午 (1-12) 小时

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

    考虑在您的情况下使用LocalDateTime

    【讨论】:

    • 谢谢您的回答。我是新人,我正在看它,但我想念它。
    • 推荐使用什么来代替简单的日期格式?
    • @NickMowen DateTimeFormatter
    猜你喜欢
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 2010-10-01
    • 1970-01-01
    • 2019-04-23
    • 2018-11-03
    相关资源
    最近更新 更多