将 1 周添加到日期,首选哪种方式?

2022-01-11 00:00:00 datetime date calendar java

我正在审查一些工作中的代码,并发现代码处理将当前时间增加 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.

相关文章