首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >时区独立

时区独立
EN

Stack Overflow用户
提问于 2012-04-24 10:24:06
回答 1查看 867关注 0票数 0

我有一个转换DateTime的类,如下所示:

代码语言:javascript
复制
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class DateFormatConverter extends XmlAdapter<String, Date> {

  private static final String XML_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS z";

  @Override
  public Date unmarshal(String xmlDate) throws Exception {
    if (xmlDate == null || xmlDate.length() == 0) 
    {
      return null;
    }    
    SimpleDateFormat xmlDateFormat = new SimpleDateFormat(XML_DATE_PATTERN);    
    return xmlDateFormat.parse(xmlDate);
  }

  @Override
  public String marshal(Date date) throws Exception {
    if (date == null) {
      return "";
    }    
    SimpleDateFormat xmlDateFormat = new SimpleDateFormat(XML_DATE_PATTERN);    
    return xmlDateFormat.format(date);
  }
}

我的单元测试:

代码语言:javascript
复制
public void testMarshalDate() throws Exception {

    DateFormatConverter converter = new DateFormatConverter();
    SimpleDateFormat dateFormater  = new SimpleDateFormat("MM-dd-yyyy");
    Date date = dateFormater.parse("10-13-2011");

    String marshalledDate = converter.marshal(date);

    String timezone = Calendar.getInstance().getTimeZone().getDisplayName(true, TimeZone.SHORT);

    System.out.println("Default Timezone:" + TimeZone.getDefault().getDisplayName(true, TimeZone.SHORT));
    System.out.println("Timezone of formatter:" + dateFormater.getTimeZone().getDisplayName(true, TimeZone.SHORT));
    System.out.println("Timezone:" + timezone);
    System.out.println("MarshaledDate: " + marshalledDate);

    assertEquals("Marshalled date string is not expected.", "2011-10-13 00:00:00.000 " + timezone, marshalledDate);
  }

控制台中的输出是:

代码语言:javascript
复制
Default Timezone:ICST
Timezone of formatter:ICST
Timezone:ICST
MarshaledDate: 2011-10-13 00:00:00.000 ICT

例外是:

代码语言:javascript
复制
Marshalled date string is not expected. expected:<...S...> but was:<......>
junit.framework.ComparisonFailure: Marshalled date string is not expected. expected:<...S...> but was:<......>

为什么封送日期有时区ICT,而我所在位置的默认时区是ICST。我该怎么做才能使时区独立?

EN

回答 1

Stack Overflow用户

发布于 2012-04-24 10:31:03

我怀疑你看到了“部分时区”和“时区名称”之间的区别。例如,英国的时区使用GMT和BST,它们实际上都是时区的一部分,ID为"Europe/London“,不过我不知道在这种情况下显示名称是什么。

如果这里不需要默认时区,则在创建时区时,将其指定为格式中类似UTC的内容。(在构造函数调用后调用setTimeZone。)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10296083

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档