为JodaTime Instant添加一些天

时间:2009-06-29 14:46:55

标签: java datetime jodatime

我正在尝试编写一个简单的实用工具方法,用于向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边界的事实。任何更好的实现方法的想法都将受到赞赏。

3 个答案:

答案 0 :(得分:8)

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

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

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

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

答案 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();
}