2011-05-26 61 views

回答

6

你並不需要在本機上進行切換 - 只問它正確的毫秒數:

return new Date(d.getTime() + unit.toMillis(span)); 

在另一方面,我肯定會嘗試使用Joda代替:)

2

有沒有圖書館這樣做? Apache的公共?喬達?

是的,如果TimeUnit不是強制性的,Jodatime提供了方便(和DST安全!)方法這一點。

DateTime now = new DateTime(); 
DateTime tomorrow = now.plusDays(1); 
DateTime lastYear = now.minusYears(1); 
DateTime nextHour = now.plusHours(1); 
// ... 

探索DateTime API瞭解更多方法。

0

正確的做法是不平凡的。你有兩種情況(假設你不介意忽略閏秒)。

如果你想詮釋TimeUnit.DAYS的確切24小時(而不是取決於DST更改23日和25小時的東西),那麼你可以簡單地添加毫秒:

public static Date add(Date base, long span TimeUnit unit) { 
    return new Date(base.getTime() + unit.toMillis(span); 
} 

如果你想要識別DST,則需要特殊情況DAYS:

public static Date add(Date base, long span TimeUnit unit) { 
    if (TimeUnit.DAYS.equals(unit)) { 
    Calendar c = Calendar.getInstance(); 
    c.setTime(base); 
    c.add(Calendar.DAY_OF_MONTH, (int) span); 
    return c.getTime(); 
    } 
    return new Date(base.getTime() + unit.toMillis(span); 
} 
相關問題