2009-06-29 47 views
6

我正在嘗試編寫一個簡單的實用程序方法,用於將某天添加到喬達時間instant。這是我的第一個刺。將某天添加到JodaTime即時

/** 
* Adds a number of days specified to the instant in time specified. 
* 
* @param instant - the date to be added to 
* @param numberOfDaysToAdd - the number of days to be added to the instant specified 
* @return an instant that has been incremented by the number of days specified 
*/ 
public static Instant addNumberOfDaysToInstant(final Instant instant, final int numberOfDaysToAdd) { 
    Days days = Days.days(numberOfDaysToAdd); 
    Interval interval = new Interval(instant, days); 
    return interval.getEnd().toInstant(); 
} 

也能正常工作在大多數情況下,當你考慮例如,當加入的天數將跨越的BST/GMT邊界以外。這是一個小例子。

public class DateAddTest { 

/** * 區使用的輸入和輸出 */ 私有靜態最後DateTimeZone ZONE = DateTimeZone.forId( 「歐洲/倫敦」);

/** 
* Formatter used to translate Instant objects to & from strings. 
*/ 
private static final DateTimeFormatter FORMATTER = DateTimeFormat.forPattern(DATE_FORMAT).withZone(ZONE); 


/** 
* Date format to be used 
*/ 
private static final String DATE_FORMAT = "dd/MM/yyyy"; 


public static void main(String[] args) { 

DateTime dateTime = FORMATTER.parseDateTime("24/10/2009"); 
Instant toAdd = dateTime.toInstant(); 
Instant answer = JodaTimeUtils.addNumberOfDaysToInstant(toAdd, 2); 

System.out.println(answer.toString(FORMATTER)); //25/10/2009 
} 

}

我覺得這個問題是因爲該區間沒有考慮到acount的事實,它已經越過邊界BST。任何更好的方法來實現這個想法將不勝感激。

+1

什麼時區你期待從即時參數創建?它會一致嗎?這個計算沒有意義,因爲你無法利用Jon提出的原始修正。 – laz 2009-06-29 17:01:02

回答

0

這是選擇的解決方案。

/** 
* Zone to use for input and output 
*/ 
private static final DateTimeZone ZONE = DateTimeZone.forId("Europe/London"); 

/** 
* Adds a number of days specified to the instant in time specified. 
* 
* @param instant - the date to be added to 
* @param numberOfDaysToAdd - the number of days to be added to the instant specified 
* @return an instant that has been incremented by the number of days specified 
*/ 
public static Instant addNumberOfDaysToInstant(final Instant instant, final int numberOfDaysToAdd) { 
    return instant.toDateTime(ZONE).withFieldAdded(DurationFieldType.days(), numberOfDaysToAdd).toInstant(); 
} 
+4

這更簡單: 返回instant.toDateTime(ZONE).plusDays(numberOfDaysToAdd).toInstant(); – JodaStephen 2009-07-31 09:04:51

7

如果要處理日期,請勿使用瞬時值。我懷疑它正確地增加了48小時的時間。使用LocalDate代替,然後使用plusDays方法。

如果您想知道在指定時刻n天后發生的時刻,在一天的同一時刻,我們無疑可以找到一種方法(將瞬間分成LocalDateLocalTime,提前LocalDate,然後重新組合,或者檢查LocalDateTime是否按你的要求做),但是如果原始時間在新的一天出現兩次,或者根本不發生,你需要計算出你想要發生的事情。

編輯:好吧,所以你需要立即工作。這是否必須在原始時區?你能使用UTC嗎?這將消除DST問題。如果不是的話,你希望在模糊或不存在的情況下做什麼(例如,在每次轉換之前的上午12點30分)。

+0

我知道在這種情況下LocalDate比瞬間更適合使用,但由於其他限制而無法更改。 – 2009-06-29 14:55:10

2

假設你的代碼的其餘部分:

public static void main(String[] args) { 

    DateTime dateTime = FORMATTER.parseDateTime("24/10/2009"); 
    Instant pInstant = dateTime.withFieldAdded(DurationFieldType.days(),2).toInstant(); 
    System.out.println("24/10/2009 + 2 Days = " + pInstant.toString(FORMATTER)); 
}