我正在尝试编写一个简单的实用程序方法,用于将整数天数添加到 Joda time instant。这是我的第一个刺。
/**
* 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 {
/** * 用于输入和输出的区域 */ private static final DateTimeZone ZONE = DateTimeZone.forId("Europe/London");
/**
* 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
}
}
我认为这个问题是因为间隔没有考虑到它已经越过 bst 边界的事实。任何关于实现这一点的更好方法的想法都将不胜感激。