开发者

java - cycle through time for a day

I need to iterate throught the time for one day. I have the starting time: 00:00 and the end time: 23:59. I want to cycl开发者_高级运维e through every minute of an hour.

How can I achieve this in Java? Does any Java library for this exist?


for (int hour = 0; hour <= 23; hour++) {
    for (int minute = 0; minute <= 59; minute++) {
        // ...
    }
}


JODA is nice for date and time manipulation. You might find the LocalTime class interesting: http://joda-time.sourceforge.net/apidocs/org/joda/time/LocalTime.html#LocalTime(int, int)


1 hour is 60 minutes. 60 minutes x 24 hours = 1440 minutes per day.

int minutes;  
for ( minutes = 1440 ; minutes > 0; minutes-- ) //  00:00 - 23:59
{
    // YOUR CODE
}


This is simple and separates the data and format:

for(int minutes = 0; minutes < 1440; minutes++) //1440 = 24 * 60
    System.out.println(String.format("%d:%2d", minutes/60, minutes%60));

If you want to comma delimit as you showed above you could join the result of a custom anonymous iterator or do this:

for(int minutes = 0; minutes < 1440; minutes++) //1440 = 24 * 60
    System.out.print(String.format("%d:%2d%s", minutes/60, minutes%60, minutes<1439?", ":""));


You can loop through the minutes of each hour and hour of a day with a simple loop and modulo

while hour < 24:
    mins = (mins + 1) % 60
    hour += mins == 0 ? 1 : 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜