JJunior
JJunior

Reputation: 2849

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 cycle through every minute of an hour.

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

Upvotes: 3

Views: 2656

Answers (5)

Peter DeWeese
Peter DeWeese

Reputation: 18333

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?", ":""));

Upvotes: 1

Garee
Garee

Reputation: 433

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
}

Upvotes: 1

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)

Upvotes: 1

Matti Lyra
Matti Lyra

Reputation: 13088

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

Upvotes: 0

Vivien Barousse
Vivien Barousse

Reputation: 20885

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

Upvotes: 5

Related Questions