Adding a number of days to a JodaTime Instant

删除回忆录丶 提交于 2019-12-05 05:55:44

If you want to deal with dates, don't use instants. I suspect it's correctly adding 48 hours to the instant.

Use a LocalDate instead, and then the plusDays method.

If you want to know the instant that occurs n days after the specified instant, at the same time of day, we could no doubt work out a way of doing that (split the instant into a LocalDate and a LocalTime, advance the LocalDate and then reassemble, or check whether LocalDateTime does what you want) but you need to work out what you want to happen if the original time occurs twice on the new day, or doesn't occur at all.

EDIT: Okay, so you need to work with an instant. Does that have to be in an original time zone? Could you use UTC? That would take away the DST issues. If not, what do you want it to do in cases of ambiguity or non-existence (e.g. at 12.30am before each of the transitions).

Assuming the rest of your code:

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

This is the solution that was chosen.

/**
* 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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!