如何计算下周?

时间:2015-09-16 05:31:05

标签: java time

我想精确计算从给定日期开始一周的时间,但我得到的输出提前一小时。

代码:

long DURATION = 7 * 24 * 60 * 60 * 1000;
System.out.println("    now: " + new Date(System.currentTimeMillis()));
System.out.println("next week: " + new Date(System.currentTimeMillis() + DURATION));

输出:

now: Wed Sep 16 09:52:36 IRDT 2015
next week: Wed Sep 23 08:52:36 IRST 2015

如何正确计算?

4 个答案:

答案 0 :(得分:13)

永远不要依赖于毫秒算术,有太多的规则和陷阱使其具有任何价值(即使在很短的时间内),而是使用专用库,如Java 8的Time API, JodaTime甚至Calendar

Java 8

LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.plusDays(7);

System.out.println(now);
System.out.println(then);

哪个输出

2015-09-16T15:34:14.771
2015-09-23T15:34:14.771

JodaTime

LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.plusDays(7);

System.out.println(now);
System.out.println(then);

哪个输出

2015-09-16T15:35:19.954
2015-09-23T15:35:19.954

日历

当您无法使用Java 8或JodaTime时

Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DATE, 7);
Date then = cal.getTime();

System.out.println(now);
System.out.println(then);

哪个输出

Wed Sep 16 15:36:39 EST 2015
Wed Sep 23 15:36:39 EST 2015

nb:"问题"你似乎一直没有问题,但事实上,在这期间,你的时区似乎已经进入/退出了一天的节约,所以Date正在显示时间,用它和#39;正确的偏移量

答案 1 :(得分:1)

试试这个

Calendar cal = Calendar.getInstance();

System.out.println(cal.getTime());

cal.add(Calendar.DAY_OF_MONTH, 7);

System.out.println(cal.getTime());

答案 2 :(得分:1)

不同之处在于时区不同。 IRDT为+0430,IRST为+0330

要解决此问题,您可以使用 JodaTime

LocalDateTime now = LocalDateTime.now();
LocalDateTime nextweek = now.plusDays(7);
System.out.println(now);
System.out.println(nextweek);

答案 3 :(得分:1)

正如其他人所说。最好使用Calendar或JodaTime库。 但问题是为什么你没有得到理想的结果。 这是因为currentTimeMillis()计算“计算机时间”和协调世界时(UTC)之间的时间。现在考虑以下案例。

long DURATION = 7 * 24 * 60 * 60 * 1000;
Date now = new Date();
Date nextWeek = new Date(now.getTime() + DURATION);
System.out.println("      now: " + now);
System.out.println("next week: " + nextWeek);

此处Date.getTime()每次从格林威治标准时间00:00:00开始计算时间,然后转换为字符串时为您的当地时区计算时间。

修改: 我错了。原因是simon说的。

  

实际的“原因”是IRDT(伊朗日光时间)在9月结束   22。这就是为什么OP的帖子中的第一个日期(9月16日)是   显示为IRDT,第二个日期(9月23日)显示为   IRST。因为IRST(伊朗标准时间)比IRDT早一个小时   显示的时间是08:52:36而不是09:52:36。

相关问题