Shanmugapriyan M
Shanmugapriyan M

Reputation: 301

How to get list of times between two time in android?

Hi I want to get list of times between two time.

Example 10 PM to 6 AM

Currently i am getting 6 AM to 10 PM but it's not working for 10 PM to 6 AM

Code :

List<java.sql.Time> intervals = new ArrayList<>();
Calendar calStart = Calendar.getInstance();
calStart.set(calStart.HOUR_OF_DAY, 22);
calStart.set(calStart.MINUTE, 00);
calStart.set(calStart.AM_PM, Calendar.PM);


java.sql.Time startTime = new java.sql.Time(calStart.getTime().getTime());
Calendar calEnd = Calendar.getInstance();
calEnd.set(calEnd.HOUR_OF_DAY, 6);
calEnd.set(calEnd.MINUTE, 00);
calEnd.set(calEnd.AM_PM, Calendar.AM);


java.sql.Time endTime = new java.sql.Time(calEnd.getTime().getTime());
intervals.add(startTime);
Calendar cal = Calendar.getInstance();
cal.setTime(startTime);

while (cal.getTime().after(endTime)) {
     cal.add(Calendar.MINUTE, 15);
     intervals.add(new java.sql.Time(cal.getTimeInMillis()));
}

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
for (java.sql.Time time : intervals) {
    System.out.println(sdf.format(time));
}

Please give any suggestion

Upvotes: 1

Views: 315

Answers (1)

Adrian Coman
Adrian Coman

Reputation: 1536

When going from 10PM to 6AM, make sure you add a day as well. Or else you will have 10PM 29th of March until 6AM 29th of March while you want 6AM 30th of March.

 calendar.add(Calendar.DATE, 1);

Upvotes: 1

Related Questions