循环通过时差逻辑

时间:2014-04-08 11:37:17

标签: java jodatime

我正在使用Joda DateTime并有2个日期:

DateTime old //which is 1:46PM   
DateTime new //which is 6:46PM

注意:排除日期。

我怎样才能按顺序循环显示差异:

(打印前半小时的消息,下一个30分钟的另一条消息以及每个后续小时的另一条消息)?

我正在考虑从新日期中减去旧日期然后制作一个循环,但我没有得到逻辑。任何指针都会有所帮助。

example
If i subtract both times above, i will have an elapsed time of 5 hours.

Loop 5 hours
{
   for the first hour (print this)
   next 30minutes (print that)
   every subsequent hour (print ....)
}

1 个答案:

答案 0 :(得分:1)

我会改用LocalTime类型。如果您输入DateTime,请使用方法toLocalTime()(具有相同的时间和年表和时区)进行转换。

LocalTime start = new LocalTime(13, 46);
LocalTime end = new LocalTime(18, 46);
LocalTime current = start;

for (int i = 0; current.isBefore(end); i++) {
    // code your print action here
    current = current.plusMinutes((i < 2) ? 30 : 60);
}

然后你会得到以下时间的行动:

13:46
14:16
14:46
15:46
16:46
17:46
相关问题