2011-11-21 71 views
2

我想解析格式为"12:34:56"(来自外部Web服务)的时间值为DateCalendar或任何可以稍后与当前时间比较的内容。默认时区的Android解析时间

问题是,在Android上,DateFormat.parse似乎忽略了用户的默认时区,并将该值解析为UTC格式。鉴于此代码:

DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); 
String inTime = "12:34:56"; 
Date time = timeFormat.parse(inTime); 
Date now = new Date(); 

我让我的桌面上的通缉的结果(Java 1.6.0_29):

Thu Jan 01 12:34:56 CET 1970 
Mon Nov 21 20:53:04 CET 2011 

换句话说,字符串 “12:34:56”,在被解析默认时区。但是,在Android上,这似乎在UTC被解析,因为它是一个小时:

Thu Jan 01 11:34:56 GMT+0100 1970 
Mon Nov 21 20:53:02 GMT+0100 2011 

我甚至尝试设置使用timeFormat.setTimeZone(TimeZone.getDefault())的时区,但是这并没有帮助。有什么方法可以强制DateFormat.parse解析Android中默认(用户)时区的时间,还是我必须将所有内容都转换为UTC,然后才能使其工作?

+0

是你自己的时区吗? –

+0

是的,CET目前是GMT + 1,所以时区信息是正确的,但时间解析的时区不是。 –

+0

嘿,你如何打印这两个输出,一个是1970年,另一个是2011年?我不明白你如何得到2011年的线路。 –

回答

0

原来我真的装置有一些问题与时区。我试着在其他设备上运行代码,并按预期工作。

我解决了我的手机问题,安装了TimeZone Fixer并更新了时区信息。

我会离开我的代码,但如果问题变得更为常见,我将不得不实施一些解决方法。

-1

试试这个:

Date time = null; 
try { 
    DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); 
    timeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // Add this. "GMT" works too. 
    String inTime = "12:34:56"; 
    time = timeFormat.parse(inTime); 
} 
catch (ParseException e) { 
    e.printStackTrace(); 
    return; 
} 

// and print with: 

Log.e("Test", "TIIIIME: " + time.toGMTString()); // Not toString... 

对于我这个代码产生:1970年

1月1日12:34:56 GMT

+0

这种方法的问题是我想将此值与当前时间进行比较,该时间位于CET中,而不是UTC。因此,我想从“12:34:56”得到12:34:56 CET--这正是我在桌面上获得的。 –

+0

什么是“CET”? –

+0

[中欧时间](http://www.timeanddate.com/library/abbreviations/timezones/eu/cet.html),GMT + 1目前。 –

0

我有同样的问题:我只需要有区域设置为dateFormatter。 以下是我所做的:

public static String getDateAsString(long milliSeconds, String dateFormat) 
    { 
    // Create a DateFormatter object for displaying date in specified format. 
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat, Locale.getDefault()); 

    // Create a calendar object that will convert the date and time value in milliseconds to date. 
    Calendar calendar = Calendar.getInstance(); 
    TimeZone tz = calendar.getTimeZone(); 
    Date date = new Date(milliSeconds); 
    calendar.setTime(date); 
    calendar.setTimeZone(tz); 
    return formatter.format(calendar.getTime()); 
} 

希望它有帮助!