[英]SimpleDateFormat produces different timezone outputs in Android vs JDK
这里有很多关于SimpleDateFormat的问题,但我似乎无法在这个问题上找到任何东西。 我遇到了与Android和JDK上运行的完全相同的代码不同输出的问题。 我在Eclipse中运行并使用模拟器来测试Android。 JDK版本1.7和Android 4.4。
有关如何使用JDK样式格式生成Android输出日期的任何想法?
TimeZone GMT_ZONE = TimeZone.getTimeZone("GMT");
String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z";
final DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN, LOCALE_US);
rfc1123Format.setTimeZone(GMT_ZONE);
String dateString = rfc1123Format.format(new Date());
JDK 1.7 dateString值:星期五,2013年12月20日00:46:21 GMT
Android 4.4 dateString值:星期五,2013年12月20日00:46:21 GMT + 00:00
Android库是对Java库的模仿,但不是精确的副本。 因此甲骨文和谷歌之间的诉讼 。 所以你可能会看到行为的变化。
如果您在使用日期时间时需要一致且出色的体验,请使用第三方开源Joda-Time库。 Joda-Time旨在取代臭名昭着的java.util.Date/Calendar类。
另一个选项可能是JSR 310的Java 7 backport :与Java 8捆绑在一起的日期和时间API java.time。*类。
关于后续问题,您添加了评论:
知道什么模式会产生Android上的Fri,2013年12月20日00:46:21 GMT格式输出?
令人惊讶的是,Joda-Time 2.3似乎缺少旧版RFC 1123格式的内置格式化程序。 但是,如果您记得将DateTime转换为UTC,则以下home-brew格式似乎可以完成这项工作,如下所示。
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
DateTime nowInParis = new DateTime( DateTimeZone.forID( "Europe/Paris" ) );
DateTimeFormatter formatter = DateTimeFormat.forPattern("E, d MMM yyyy HH:mm:ss 'GMT'").withLocale( Locale.US );
String nowInParisAsStringGMT = formatter.print( nowInParis.toDateTime( DateTimeZone.UTC ) );
转储到控制台......
System.out.println( "nowInParisAsStringGMT: " + nowInParisAsStringGMT );
System.out.println( "nowInParis: " + nowInParis );
跑的时候......
nowInParisAsStringGMT: Fri, 20 Dec 2013 05:03:58 GMT
nowInParis: 2013-12-20T05:03:58.175+01:00
对于那些不想使用Joda-Time的人来说,这是Basil的答案的略微修改版本:
private String toRfc1123(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
return formatter.format(date);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.