UYAR.C
UYAR.C

Reputation: 151

How to create one hour time slots between start and end timestamp date?

I want to create one hour time slots between two date and save all one hour slots with start and end date. How can do it?

For example

start date:08/09/2019 13.00
enddate:08/09/2019 16.00

and ı want to get

08/09/2019 13.00- 08/09/2019 14.00
08/09/2019 14.00- 08/09/2019 15.00
08/09/2019 15.00- 08/09/2019 16.00 

Thanks,

Upvotes: 1

Views: 2821

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 340300

java.time

The modern solution uses the java.time classes.

LocalDateTime

Use LocalDateTime to represent a date with time-of-day. Be aware that without a time zone of offset-from-UTC, this type does not represent a moment, is not a point in the timeline.

LocalDateTime start = LocalDateTime.parse( "2019-09-08T13:00:00" ) ;
LocalDateTime stop = LocalDateTime.parse( "2019-09-08T16:00:00" ) ;

Loop, hour by hour

Loop, adding an hour at a time, until past the stopping point.

List< LocalDateTime > slots = new ArrayList<>() ;
LocalDateTime ldt = start ;
while (
    ldt.isBefore( stop ) 
) {
    slots.add( ldt ) ;
    // Prepare for the next loop. 
    ldt = ldt.plusHours( 1 ) ;
}

ZonedDateTime

If you want to track actual moments, specify a time zone.

ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
LocalDateTime ldt = LocalDateTime.parse( "2019-09-08T13:00:00" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

Then follow the same logic we saw in code above. Loop hour-by-hour, collecting ZonedDateTime objects.

Upvotes: 3

Related Questions