为JodaTime Instant添加一些天数

我正在尝试编写一个简单的实用程序方法,用于向Joda时刻添加整数天。 这是我的第一次尝试。

/** * 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边界的事实。 任何更好的实现方法的想法将不胜感激。

如果您想处理日期 ,请不要使用时刻。 我怀疑这是正确添加48小时的瞬间。

改为使用LocalDate ,然后使用plusDays方法。

如果您想知道在指定时刻后n天发生的瞬间,在一天的同一时间,我们无疑可以找到一种方法(将瞬间拆分为LocalDateLocalTime ,推进LocalDate然后重新组装,或检查LocalDateTime是否符合您的要求,但如果原始时间在新的一天发生两次,或者根本不发生,您需要计算出您想要发生的事情。

编辑:好的,所以你需要立即工作。 那是否必须在原始时区? 你能用UTC吗? 这会夺走DST问题。 如果不是,那么在模糊或不存在的情况下你想要它做什么(例如在每次转换之前的12:30)。

假设你的其余代码:

 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)); } 

这是选择的解决方案。

 /** * 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(); }