JodaTime:如何在不同的时区找到未来的时间



我需要找到时间点,下一次是奥克兰(新西兰(早上7:00

我正在使用joda时间2.6

    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.6</version>
    </dependency>

使用以下进行测试时

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

如果我在奥克兰的午夜后运行上述,那没关系,这是

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

但是,如果我在奥克兰午夜前运行上述,我会得到过去的早上7点。。。

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

在更改时间时,有没有办法告诉joda前进的时间?

我认为最明显的解决方案可能是正确的

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

你只需检查奥克兰是否已经有超过7:00的病例,如果是,只需增加天数。

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

打印:

2016-09-01T21:07:13.444+05:30
2016-09-02T00:30:00.047+05:30

新西兰的上午7点将是IST的00:30,根据谷歌,这似乎是正确的

*7:00 AM Friday, in Auckland, New Zealand is
12:30 AM Friday, Indian Standard Time (IST)*

相关内容

  • 没有找到相关文章

最新更新