I need to find the point in time, when it will next be 7:00 in the morning in Auckland (in New Zealand)
I am using joda-time 2.6
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.6</version>
</dependency>
When testing with the following
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class FindDateTimeInFuture {
static DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS z Z");
public static void main(String[] args) {
// Use UTC as application wide default
DateTimeZone.setDefault(DateTimeZone.UTC);
System.out.println("now UTC = " + formatter.print(DateTime.now()));
System.out.println("now in Auckland = " + formatter.print(DateTime.now(DateTimeZone.forID("Pacific/Auckland"))));
System.out.println("7 AM Auckland = " + formatter.print(DateTime.now(DateTimeZone.forID("Pacific/Auckland")).withTime(7, 0, 0, 0)));
}
}
If I run the above after Midnight in Auckland, it is fine, it is
now UTC = 2016-09-01 13:37:26.844 UTC +0000
now in Auckland = 2016-09-02 01:37:26.910 NZST +1200
7 AM Auckland = 2016-09-02 07:00:00.000 NZST +1200
^ ok, in the future
But, if I run the above before Midnight in Auckland, I get the 7 AM in the past ...
now UTC = 2016-09-01 09:37:48.737 UTC +0000
now in Auckland = 2016-09-01 21:37:48.831 NZST +1200
7 AM Auckland = 2016-09-01 07:00:00.000 NZST +1200
^ ko, in the past
Is there a way to tell joda-time to go forward when changing the time ?
An interval in Joda-Time represents an interval of time from one instant to another instant. Both instants are fully specified instants in the datetime continuum, complete with time zone.
Joda-Time provides support for multiple calendar systems and the full range of time-zones. The Chronology and DateTimeZone classes provide this support. Joda-Time defaults to using the ISO calendar system, which is the de facto civil calendar used by the world.
Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat. Low level - builder.
Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.
I think the most obvious solution may be correct one
DateTime nowAuckland =
DateTime.now(DateTimeZone.forID("Pacific/Auckland"));
boolean addDay = nowAuckland.getHourOfDay() >= 7;
DateTime aucklandAt700 = nowAuckland.withTime(7, 0, 0, 0);
if (addDay) {
aucklandAt700 = aucklandAt700.plusDays(1);
}
You can just check if there is already more than 7:00
at Auckland and if so just increment number of days.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With