2013-10-28 48 views
1

我在我的代码中使用了SimpleDateFormat,如下所示。SimpledateFormat为不同的Android版本返回不同的值

SimpleDateFormat sdf = new SimpleDateFormat("ZZZZ"); 

我想显示结果为GMT-05:00。我在Android 4.3中运行我的代码。它返回了与我预期相同的结果。但是,上述代码行返回-05:00而不是GMT-05:00,适用于Android版本4.0,4.1和4.2(缺少GMT)。我很困惑。我已经阅读了Android的SimpleDateFormat

任何人都可以给我一些想法吗?

回答

0

由于文件只显示最新的版本,我找不到是否在Android 4.3之前总是返回SimpleDateFormat sdf = new SimpleDateFormat("ZZZZ");GMT-05:00

我能想到的最佳近似值是SimpleDateFormat sdf = new SimpleDateFormat("'GMT'Z", Locale.US);明确添加GMT的时间格式,但时间格式不含冒号(例如GMT-0500)。


编辑:如果你能保证在4.1和4.2,您的代码返回-05:00,那么我认为你可以添加版本检查,并决定哪些SimpleDateFormat将被使用。

if (Build.VERSION.SDK_INT >= 18) { 
    SimpleDateFormat sdf = new SimpleDateFormat("ZZZZ", Locale.US); 
} else { 
    SimpleDateFormat sdf = new SimpleDateFormat("'GMT'ZZZZ", Locale.US); 
} 
+0

嗨@antimo,我现在在我的代码中使用相同的逻辑。无论如何感谢您的建议。这很奇怪。 :d – Ibungo

0

您可以使用DateFormats到日期转换为字符串,在任何时区:

DateFormat df = DateFormat.getTimeInstance(); 
df.setTimeZone(TimeZone.getTimeZone("gmt")); 
String gmtTime = df.format(new Date()); 
+0

感谢您的建议@ ling.s – Ibungo

0

检查了这一点也是:

SimpleDateFormat dateFormatGmt = new SimpleDateFormat("dd:MM:yyyy"); 
    dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT")); 
    System.out.println(dateFormatGmt.format(new Date())); 
+0

感谢您的回复。它并没有解决我的问题。 – Ibungo

0

我碰到了类似的问题,但“ZZZZZ”,我发现,仅加入在4.3以上版本的一些SimpleDateFormat的修正:https://code.google.com/p/android/issues/detail?id=73209

由于“ZZZZZ”和“ZZZZ”被记录在案在一起,我假设行为如预期的4.0,4.1 & 4.2