Add 1 Week to a Date, which way is preferred?(将 1 周添加到日期,首选哪种方式?)
问题描述
我正在审查一些工作中的代码,并发现代码处理将当前时间增加 1 周的方式不一致,我想知道是否有任何理由真正应该优先于另一个:
I am reviewing some code at work and came across an inconsistency in how the code handles adding 1 week to the current time and was wondering if there was any reason why one should really be preferred over the other:
第一个是实用方法:
public static Date addDaysToDate(final Date date, int noOfDays) {
Date newDate = new Date(date.getTime());
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(newDate);
calendar.add(Calendar.DATE, noOfDays);
newDate.setTime(calendar.getTime().getTime());
return newDate;
}
第二个使用简单的毫秒算术:
And the second used simple millisecond arithmetic:
long theFuture = System.currentTimeMillis() + (86400 * 7 * 1000);
Date nextWeek = new Date(theFuture);
第二种方法显然使用幻数"来定义一周,但这可以移动到一个常数 MILLISECONDS_IN_ONE_WEEK = 86400 * 7 * 1000
那么除此之外,还有什么原因这些方法中的哪一种应该优于其他方法?
The second method obviously uses 'magic numbers' to define a week, but this could be moved to a constant MILLISECONDS_IN_ONE_WEEK = 86400 * 7 * 1000
So other than that, is there any reasons why one of these methods should be preferred over the other?
基本上我想更改代码以使其始终保持一致,但我不完全确定要删除哪一个.因此,任何一种或另一种方式的论点都是有用的.
Basically I want to change the code to be consistent throughout, but I'm not entirely sure which one to remove. So any arguments one way or the other would be useful.
推荐答案
这两种方法在夏令时边界上的行为会有所不同.第一种方法将继续返回一天中的同一时间,无论夏令时状态如何.第二种方法将返回随着夏令时开始和停止而在每个方向变化一小时的时间.
The two methods will behave differently on daylight savings boundaries. The first method will continue returning the same time of the day, regardless of daylight savings status. The second method will return times which vary an hour in each direction as daylight savings time starts and stops.
这篇关于将 1 周添加到日期,首选哪种方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 1 周添加到日期,首选哪种方式?


基础教程推荐
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01