問題描述
我正在審查一些工作中的代碼,并發(fā)現(xiàn)代碼處理將當(dāng)前時間增加 1 周的方式不一致,我想知道是否有任何理由真正應(yīng)該優(yōu)先于另一個:
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;
}
第二個使用簡單的毫秒算術(shù):
And the second used simple millisecond arithmetic:
long theFuture = System.currentTimeMillis() + (86400 * 7 * 1000);
Date nextWeek = new Date(theFuture);
第二種方法顯然使用幻數(shù)"來定義一周,但這可以移動到一個常數(shù) MILLISECONDS_IN_ONE_WEEK = 86400 * 7 * 1000
那么除此之外,還有什么原因這些方法中的哪一種應(yīng)該優(yōu)于其他方法?
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.
推薦答案
這兩種方法在夏令時邊界上的行為會有所不同.第一種方法將繼續(xù)返回一天中的同一時間,無論夏令時狀態(tài)如何.第二種方法將返回隨著夏令時開始和停止而在每個方向變化一小時的時間.
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.
這篇關(guān)于將 1 周添加到日期,首選哪種方式?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!