格式化XmlGregorianCalendar时区问题 [英] Formatting XmlGregorianCalendar timezone issue

查看:2320
本文介绍了格式化XmlGregorianCalendar时区问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to format java XmlGregorianCalendar to "yyMMdd" string. My implementation:

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

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

April, 15 was parsed as April, 14. What I'm doing wrong? When I should set timezone?

推荐答案

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

It was parsed as midnight on April 15th UTC. It was then formatted as 8pm on April 14th EDT, which is correct as EDT is four hours behind UTC.

请注意, Date.toString()始终使用本地时区 - 一个 Date 对象没有哪个时间的概念区域在。

Note that Date.toString() always uses the local time zone - a Date object has no concept of which time zone it's in.

使用默认时区,您的格式化值也,因为您没有指定时区。日历值( gc )以UTC为单位,但格式化时将从格式化程序应用时区(格式化 Date 的价值,其中没有是一个时区)。

Your formatted value is also using the default time zone, as you haven't specified a time zone. The calendar value (gc) is in UTC, but when you format it, it will apply the time zone from the formatter (as you format the Date value, which doesn't have a time zone).

目前还不清楚你正在尝试实现什么,但希望这将有所帮助。除此之外,我强烈建议您使用 Joda时间,如果可能的话,它会使很多这个更清楚。

It's not clear what you were trying to achieve, but hopefully that will help. As an aside, I'd strongly recommend that you use Joda Time instead if you possibly can - it makes a lot of this much clearer.

这篇关于格式化XmlGregorianCalendar时区问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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