Reputation: 1925
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 ?
Upvotes: 5
Views: 546
Reputation: 11250
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.
Upvotes: 3
Reputation: 4948
DateTime nowAuckland = DateTime.now(DateTimeZone.forID("Pacific/Auckland"));
DateTime currentTimeNow = DateTime.now(DateTimeZone.getDefault());
DateTime aucklandAt700 = nowAuckland.withTime(7, 0, 0, 0);
System.out.println(currentTimeNow);
Duration duration = new Interval(nowAuckland, aucklandAt700).toDuration();
System.out.println(currentTimeNow.plusMillis((int) duration.getMillis()));
Prints :
2016-09-01T21:07:13.444+05:30
2016-09-02T00:30:00.047+05:30
7 AM in NZ will be 00:30 in IST , which seems right as per google
*7:00 AM Friday, in Auckland, New Zealand is
12:30 AM Friday, Indian Standard Time (IST)*
Upvotes: 0
Reputation: 4173
private DateTime getNextDateTime(DateTime now, int hour)
{
DateTime nextDateTime = now.withTime(hour, 0, 0, 0);
if(nextDateTime.isBefore(now))
{
nextDateTime = nextDateTime.plusDays(1);
}
return nextDateTime;
}
Upvotes: 1