Java日历:为时区腾出时间

时间:2011-09-20 09:27:47

标签: java date calendar

以下作品(显示UTC时间)

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
System.out.println(new Date());

但这不是(显示当地时间)

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    System.out.println(cal.getTime());
    System.out.println(new Date());

有什么简单的东西,我错过了吗?

2 个答案:

答案 0 :(得分:5)

您正在打印Date.toString()的结果,始终使用默认时区。

我建议您改用DateFormat,这更适合格式化日期。 Date.toString实际上只适用于调试 - 它无法控制格式。

或者,使用Joda Time进行所有日期和时间操作 - 这是一个更好的API开始:)

答案 1 :(得分:1)

要获取为其他时区格式化的日期,请使用SimpleDateFormat并在其中设置时区(默认情况下,它使用本地时区)。

尝试这种方式:

SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyyy HH:mm:SS Z");
f.setTimeZone(TimeZone.getTimeZone("UTC"));
Calendar cal = Calendar.getInstance();
System.out.println(f.format(cal.getTime()));
System.out.println(new Date());