2012-04-24 64 views
0

我有一個轉換日期時間如下一類:時區獨立

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

我懷疑你看到「部分時區」和「時區名稱」之間的區別。例如,英國的區域使用GMT和BST,兩者都是真的時區的一部分,ID爲「歐洲/倫敦」,但我不知道在這種情況下顯示名稱是什麼。

如果您不需要需要此處的默認時區,請在創建格式時將其指定爲UTC格式。 (調用構造函數後調用setTimeZone

+0

我修好了,問題是這行的原因: – Barcelona 2012-04-24 13:42:06

+0

我修好了,問題是這行的原因:String timezone = Calendar.getInstance()。getTimeZone( ).getDisplayName(true,TimeZone.SHORT);讓true變爲false,因爲默認SimpledateFormat使用非日光格式(在這種情況下是ICT)。 – Barcelona 2012-04-24 14:36:35