【问题标题】:Formatting XmlGregorianCalendar timezone issue格式化 XmlGregorianCalendar 时区问题
【发布时间】:2012-03-03 17:11:16
【问题描述】:

我需要将 java XmlGregorianCalendar 格式化为“yyMMdd”字符串。 我的实现:

XMLGregorianCalendar date = getDate(); //getting the date

if (date != null) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");

        LOG.debug("Parsing date...");
        LOG.debug("XML Date: " + date);
        LOG.debug("XML Date timezone: " + date.getTimezone());

        GregorianCalendar gc = date.toGregorianCalendar();

        LOG.debug("Gregorian calendar: " + gc.toString());
        LOG.debug("Gregorian calendar timezone id: " + gc.getTimeZone().getID());

        Date d = gc.getTime();

        LOG.debug("Date: " + d.toString());

        String formatted = sdf.format(d);

        LOG.debug("Formatted: " + formatted);
}

我在日志中看到的:

Parsing date...
XML Date: 1943-04-15T00:00:00.000Z
XML Date timezone: 0
Gregorian calendar: java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT+00:00",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=1943,MONTH=3,WEEK_OF_YEAR=1,WEEK_OF_MONTH=1,DAY_OF_MONTH=15,DAY_OF_YEAR=1,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]
Gregorian calendar timezone id: GMT+00:00
Date: Wed Apr 14 20:00:00 EDT 1943
Formatted: 430414

April, 15 被解析为 April, 14。我做错了什么?我应该什么时候设置时区?

【问题讨论】:

    标签: java date timezone format


    【解决方案1】:

    它被解析为 4 月 15 日午夜 UTC。然后它被格式化为 4 月 14 日晚上 8 点EDT,这是正确的,因为 EDT 比 UTC 晚 4 小时。

    请注意,Date.toString() 始终使用 本地 时区 - Date 对象不知道它所在的时区。

    您的格式化值使用默认时区,因为您没有指定时区。日历值 (gc) 采用 UTC,但是当您对其进行格式化时,它将应用格式化程序中的时区(当您格式化 Date 值时,它没有时区)。

    目前尚不清楚您要达到什么目标,但希望这会有所帮助。顺便说一句,我强烈建议您尽可能使用 Joda Time 来代替 - 它使很多事情变得更加清晰。

    【讨论】:

    • 我试图用 XmlCalendar 的时区解析它。现在我明白我应该为我的格式化程序设置时区。感谢您的解释。
    猜你喜欢
    • 2012-09-11
    • 1970-01-01
    • 2018-05-22
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 2021-03-27
    相关资源
    最近更新 更多