如果我执行:
System.out.println("Formatter: " + String.format("%1$tH:%1$tM:%1$tS %1$tz %1$tZ", now));
System.out.println("SimpleDF : " + new SimpleDateFormat("HH:mm:ss Z z").format(now));
我希望结果是一样的。如果我检查自动调整夏令时值开始变化:
without dst (as expected, gmt=9:48): Formatter: 10:48:16 +0100 GMT+01:00 SimpleDF : 10:48:16 +0100 GMT+01:00 with dst (gmt varies between formatter and sdf ???): Formatter: 11:47:54 +0100 CEST SimpleDF : 11:47:54 +0200 CEST
在 win xp 上运行,在 java 1.6-10/13 和 1.5.0-14 上具有相同的结果,locale en_US。你怎么看,一个错误?
最佳答案
正确的方法是使用SimpleDateFormat
(或者说DateFormat
)对象。 String.format 用于格式化由于对传递的对象调用 toString()
方法而返回的字符串。第一行代码可以分解成类似这样的内容,
String temp = now.toString();
System.out.println("Formatter: " + String.format("%1$tH:%1$tM:%1$tS %1$tz %1$tZ", temp));
临时字符串对象使用默认的语言环境和设置进行格式化,因此可能无法保证完美的结果(根据我的经验)。
SimpleDateFormat()
处理 Date
对象并访问属性并确保所有 DST 补丁。
关于java - 如何(正确)使用 String.format %tz 报告时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/700751/