加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何计算下周?

发布时间:2020-12-14 23:49:08 所属栏目:Java 来源:网络整理
导读:我想精确地计算一个给定日期一周的时间,但是我得到的输出是早一个小时. 码: long DURATION = 7 * 24 * 60 * 60 * 1000;System.out.println(" now: " + new Date(System.currentTimeMillis()));System.out.println("next week: " + new Date(System.currentT
我想精确地计算一个给定日期一周的时间,但是我得到的输出是早一个小时.

码:

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

如何正确计算?

解决方法

从来没有依赖于毫秒的算术,有太多的规则和陷阱使它成为任何价值(即使在一小段时间内),而是使用专用库,如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正在显示时间,这是正确的偏移

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读