-4

JAVA | How to find date and time coming in between two given date and time that increment by 5 minutes?

For example, if the starting point is [29/1/2017 5:40:00 AM]

And the stopping point is [29/1/2017 6:00:00 AM]

The list (based on starting and stopping points ) and it is must be like this

29/1/2017  5:40:00 AM                                                                     
29/1/2017  5:45:00 AM    
29/1/2017  5:50:00 AM     
29/1/2017  5:55:00 AM     
29/1/2017  6:00:00 AM

Please don’t use JODA.

Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76

2 Answers2

2

Heres the Java8 Version using the new DateTime API. If you're on Java8 you should use this code.

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("d/M/u h:m:s a");
LocalDateTime dateTime = LocalDateTime.parse("29/1/2017 5:40:00 AM", dateTimeFormatter);
LocalDateTime endDateTime = LocalDateTime.parse("29/1/2017 6:00:00 AM", dateTimeFormatter);

for(; !dateTime.isAfter(endDateTime); dateTime = dateTime.plusMinutes(5))
    System.out.println(dateTime.format(dateTimeFormatter));
Alex_M
  • 1,824
  • 1
  • 14
  • 26
1

If you are not interested in using JODA, you can achieve this using java.util.Calendar. Say, you have two String objects representing two dates:

String startDateStr = "29/1/2017 5:40:00 AM";
String endDateStr = "29/1/2017 6:00:00 AM";

Create a DateFormat to parse these:

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");

Now, create two java.util.Date objects and two java.util.Calendar instances representing the dates:

Date startDate = dateFormat.parse(startDateStr);
Date endDate = dateFormat.parse(endDateStr);

Calendar startDateCal = Calendar.getInstance();
startDateCal.setTime(startDate);

Calendar endDateCal = Calendar.getInstance();
endDateCal.setTime(endDate); 

Now, you can iterate through the dates like shown below:

for(Date d = startDateCal.getTime(); startDateCal.before(endDateCal); startDateCal.add(Calendar.MINUTE, 5)){
    d = startDateCal.getTime();
    System.out.println(dateFormat.format(d.getTime()));
}

I thing, this is what you are trying to achieve.

Shyam Baitmangalkar
  • 1,075
  • 12
  • 18
  • thank you , this is exactly what I need – eng.nassar Jan 29 '17 at 05:08
  • FYI, the old [`Calendar`](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html) and [`Date`](http://docs.oracle.com/javase/8/docs/api/java/util/Date.html) classes are now [legacy](https://en.wikipedia.org/wiki/Legacy_system). Supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. – Basil Bourque Jan 29 '17 at 05:52