我正在尝试编写一个简单的实用工具方法,用于向Joda时间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边界的事实。任何更好的实现方法的想法都将受到赞赏。
答案 0 :(得分:8)
如果您想处理日期,请不要使用瞬间。我怀疑这是正确的加入48小时。
改为使用LocalDate
,然后使用plusDays
方法。
如果您想知道在指定时刻后n天发生的瞬间,在一天的同一时间,我们无疑可以找到一种方法(将瞬间分成LocalDate
和LocalTime
,推进LocalDate
,然后重新组合,或检查LocalDateTime
是否符合您的要求,但如果原始时间在新版本上出现两次,您需要弄清楚您想要发生的事情一天,或根本不会发生。
答案 1 :(得分: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));
}
答案 2 :(得分: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();
}