У меня есть класс, который преобразует 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:<......>
Почему маршалинская дата имеет временные зоны ИКТ, а часовой пояс по умолчанию - ICST. Как я могу исправить, чтобы сделать Timezone независимым?
Я исправил его, проблема является причиной этой строки: – Barcelona
Я исправил это, проблема является причиной этой строки: String timezone = Calendar.getInstance(). GetTimeZone () .getDisplayName (true, TimeZone.SHORT); Пусть значение true соответствует false, потому что по умолчанию SimpledateFormat использует формат не дневного (в данном случае - ИКТ). – Barcelona