当我在网上搜索“如何将 Calendar
转换为 String
”时,我找到的所有结果都建议先转换为 Date
然后转换 Date
到 String
.
问题是 Date
仅表示自纪元以来的毫秒数 - 它不考虑时区。 Calendar
这种方式更先进。
当然可以调用个人Calendar.get
创建我自己的格式化字符串的方法,但肯定有更简单的方法吗?
为了说明,我写了这段代码:
long currentTime = Calendar.getInstance().getTimeInMillis();
Calendar calendar = new GregorianCalendar();
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
calendar.setTimeInMillis(currentTime);
System.out.println(calendar.getTime().toString());
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()));
System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
在晚上 8 点 02 分从位于伦敦 (UTC+0) 的一台机器上运行这段代码时,我得到了以下结果:
Wed Nov 18 20:02:26 UTC 2015
2015-11-18 20:02:26
21
最后一行显示了根据日历时区(马德里为 UTC+1)的实际时间。现在是马德里晚上 9:02,但显然都是本地人 Date.toString
以及 DateFormat.format
方法会忽略时区,因为调用时会删除时区信息 Calendar.getTime
(类似 Calendar.getTimeInMillis
)。
鉴于此,从 Calendar
中获取格式化字符串的最佳方法是什么?哪个尊重时区?
最佳答案
在 SimpleDateFormat 对象上设置时区,然后使用 z
..
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
System.out.println(sdf.format(calendar.getTime());
关于java - 从尊重时区的日历对象中获取格式化字符串的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33789460/