我有一个转换DateTime的类,如下所示:
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);
}
}
我的单元测试:
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);
}
控制台中的输出是:
Default Timezone:ICST
Timezone of formatter:ICST
Timezone:ICST
MarshaledDate: 2011-10-13 00:00:00.000 ICT
例外是:
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。我应该如何解决使时区独立的问题?
答案 0 :(得分:0)
我怀疑你看到“时区的一部分”和“时区名称”之间的区别。例如,英国的区域使用GMT和BST,两者都是真正时区的一部分,其ID为“欧洲/伦敦”,但我不知道显示名称是什么那种情况。
如果此处 需要默认时区,请在创建时将其指定为UTC格式的内容。 (在构造函数调用后调用setTimeZone
。)