返回

格式化XmlGregorianCalendar时区问题(Formatting XmlGregorianCalendar timezone issue)

发布时间:2022-10-29 05:47:15 349
# java# java

 

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

  What I see in log:

  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 was parsed as April, 14. What I'm doing wrong? When I should set timezone?

  盾畳圭宛

  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.

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

  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).

  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.

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
notepad++格式化xml文件的方法 2022-10-29 05:12:40