为什么SimpleDateFormat改变日期? [英] Why is SimpleDateFormat changing the date?

查看:177
本文介绍了为什么SimpleDateFormat改变日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码:

  [...] 

public void testFormatDateString()抛出ParseException {

String dateString = new java.util.Date()。toString();

System.out.println(dateString);

SimpleDateFormat format = new SimpleDateFormat(EEE MMM dd HH:mm:ss z YYYY,Locale.ENGLISH);

日期日期= format.parse(dateString);

System.out.println(date.toString());





之前:
8月19日星期六18:26:11 BST 2017



之后:
Sat Jan 07 17:26:11 GMT 2017




<大写 Y 用于week year,它有364或371天,而不是通常的365或366。小写 y (它被 Date#toString 使用)一切都按预期工作:

  public void testFormatDateString()throws ParseException {

String dateString = new java.util.Date()。toString();

System.out.println(dateString);

//强制为Locale.US,因为这是硬编码在Date#toString
SimpleDateFormat format = new SimpleDateFormat(
EEE MMM dd HH:mm:ss z yyyy, Locale.US);

日期日期= format.parse(dateString);

System.out.println(date.toString());



$ b $ p $输出:

  8月19日星期六17:50:39 GMT 2017 
8月19日星期六17:50:39 GMT 2017

查看ideone.com



正如注释中所提到的,在解析 dateString Locale.US c>,因为它是在 Date#toString 中硬编码的。请参阅此问题了解详情。


Given the following code:

[...]

    public void testFormatDateString() throws ParseException {

        String dateString = new java.util.Date().toString();

        System.out.println(dateString);

        SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z YYYY", Locale.ENGLISH);

        Date date = format.parse(dateString);

        System.out.println(date.toString());
    }

[...]

Before: Sat Aug 19 18:26:11 BST 2017

After: Sat Jan 07 17:26:11 GMT 2017

Why is the date changed?

解决方案

The upper case Y is for "week year", which has 364 or 371 days instead of the usual 365 or 366. With lower case y (which is used by Date#toString) everything works as expected:

public void testFormatDateString() throws ParseException {

    String dateString = new java.util.Date().toString();

    System.out.println(dateString);

    // Force to Locale.US as this is hardcoded in Date#toString
    SimpleDateFormat format = new SimpleDateFormat(
            "EEE MMM dd HH:mm:ss z yyyy", Locale.US);

    Date date = format.parse(dateString);

    System.out.println(date.toString());
}

Output:

Sat Aug 19 17:50:39 GMT 2017
Sat Aug 19 17:50:39 GMT 2017

See on ideone.com

As mentioned in the comments, make sure to include Locale.US when parsing the dateString, as that is hardcoded in Date#toString. See this question for details.

这篇关于为什么SimpleDateFormat改变日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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