Java:比较相同时区的日期

时间:2014-12-16 18:34:05

标签: java date timezone

假设:

SimpleDateFormat sd = new SimpleDateFormat ("yy-MM-dd hh:mm:ss.SSS");
sd.setTimeZone(TimeZone.getTimeZone("GMT"));
Date d = sd.parse("a date similar to now on local computer");

如果我将d.getTime()new Date().getTime()进行比较,则值的差异超过一小时。为什么呢?

3 个答案:

答案 0 :(得分:1)

检查您的时区。您正在比较GMT中没有的时间。

答案 1 :(得分:1)

您明确将SimpleDateFormat设置为在GMT中进行解析,这意味着当您解析当前时钟时间时,您将获得格林尼治标准时间中发生该时间的时刻时区。如果您不在格林尼治标准时间区域,那么现在就不会#34;

答案 2 :(得分:1)

Date个对象对时区一无所知 - Date对象中没有明确的时区信息。 Date对象表示“绝对”时刻(它是时间戳)。这意味着你不应该将Date对象视为“某个时区的日期” - 它没有时区。

假设从某些来源获得的String包含日期和时间,但没有明确的时区,例如:2014-12-16 17:30:48.382。假设您知道此日期和时间是GMT时区。

然后,您可以使用适当的Date对象将其解析为SimpleDateFormat对象:

DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

// Set the timezone of the SimpleDateFormat to GMT, because you know the string
// should be interpreted as GMT
fmt.setTimeZone(TimeZone.getTimeZone("GMT"));

// Parse the String into a Date object
Date dateTime = fmt.parse("2014-12-16 17:30:48.382");

// Date object which is set to "now"
Date now = new Date();

// Compare it to "now"
if (dateTime.before(now)) {
    System.out.println("The specified date is in the past");
} else if (dateTime.after(now)) {
    System.out.println("The specified date is in the future");
} else {
    System.out.println("The specified date is now");
}

如果要在特定时区打印日期,请通过将SimpleDateFormat设置为适当的时区进行格式化来执行此操作。

DateFormat outfmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
outfmt.setTimeZone(TimeZone.getTimeZone("EDT"));

// Will print dateTime in the EDT timezone
System.out.println(outfmt.format(dateTime));