gpt4 book ai didi

java - SimpleDateFormat 格式日期之间的日期问题

转载 作者:行者123 更新时间:2023-12-02 05:16:50 26 4
gpt4 key购买 nike

我需要计算两个日期之间的时间段,其中一个日期是现在。我使用 SimpleDateFormat 来格式化日期。

public String getPeriod(Date endDate) {
String format;
Date now = new Date();
long period = endDate.getTime() - now.getTime();

if (now.after(endDate)) {
return "passed";
} else {
if (period < 1000 * 60 * 60)
format = "m'M' s'S'";
else if (period < 1000 * 60 * 60 * 24)
format = "k'H' m'M'";
else
format = "'Too much'";

SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(new Date(period)) + " / for testing - " + period / 3600000 + " hours";
}
}

因此,我有以下输入,例如,如果 endDate 等于 Wed Nov 12 13:30:02 EET 2014 (EST):

1 H 36 M / for testing - 22 hours

如您所见,我的测试计算和格式的方法结果不匹配。我做错了什么?

最佳答案

差异是由于时区造成的。例如,在我的例子中,给定一个小时的时间作为参数,我得到 3H 作为输出,因为日期将是 Thu Jan 01 03:00:00 EET 1970。注意 EET(我来自东欧洲)。

如果您通知 java 使用 GMT 时间,您的代码将会工作,正如新的 Date(long) 描述中所述:

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

另外,请记住,日期并不能给出完美的结果。使用以编程方式精确确定 1 小时单位的日期(无米/分钟差异),日期计算得出的偏移量为 59 分、59 秒和 999 英里。如果您需要更精确的值,则应使用纳秒。

但是,其他评论者是对的。您不应该以这种方式使用 Java 日期/日历,因为它是一个错误工厂(这只是一个极端情况)。您应该查看其他库(例如 yoda time),或者如果您只需要这样的简单计算,请自己完成。

希望有帮助。

关于java - SimpleDateFormat 格式日期之间的日期问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26865573/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com