Java – add some days for jodatime instant

I'm trying to write a simple utility method to add an integer day to joda time instant This is my first attempt

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

This works in most cases, unless you consider adding an example of days, which will allow you to cross the BST / GMT boundary This is a small example

public class DateAddTest {

/* * area for input and output * / private static final datetimezone zone 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
}

}

I think this problem is because the interval does not take into account the fact that it has crossed the BST boundary Any idea of a better implementation would be appreciated

Solution

If you want to process the date, please do not use the time I suspect it added 48 hours correctly

Use localdate instead, and then use the plusdays method

If you want to know the moment n days after the specified time, at the same time of the day, There is no doubt that we can find a way (split the moment into localdate and Localtime, push the localdate and reassemble it, or check whether the localdatetime meets your requirements. However, if the original time occurs twice on a new day or does not occur at all, you need to calculate what you want to happen

Editor: OK, so you need to work immediately Does that have to be in the original time zone? Can you use UTC? This will take away the DST problem If not, then what do you want it to do if it's fuzzy or nonexistent (e.g. 12:30 before each conversion)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>