4

I am trying to create a time range in between two times. I am able to do it in PHP This code gives the array of times with 30 minutes interval when i supply start time , end time and interval. Below is the php script.

//timerange.php


   <?php 

/** 
* create_time_range  
*  
* @param mixed $start start time, e.g., 9:30am or 9:30 
* @param mixed $end   end time, e.g., 5:30pm or 17:30 
* @param string $by   1 hour, 1 mins, 1 secs, etc. 
* @access public 
* @return void 
*/ 
function create_time_range($start, $end, $by='30 mins') { 

   $start_time = strtotime($start); 
   $end_time   = strtotime($end); 

   $current    = time(); 
   $add_time   = strtotime('+'.$by, $current); 
   $diff       = $add_time-$current; 

   $times = array(); 
   while ($start_time < $end_time) { 
       $times[] = $start_time; 
       $start_time += $diff; 
    } 
  $times[] = $start_time; 
  return $times; 
 } 

  // create array of time ranges 
  $times = create_time_range('9:30', '17:30', '30 mins'); 

   // more examples 
  // $times = create_time_range('9:30am', '5:30pm', '30 mins'); 
   // $times = create_time_range('9:30am', '5:30pm', '1 mins'); 
 // $times = create_time_range('9:30am', '5:30pm', '30 secs'); 
 // and so on 

// format the unix timestamps 
   foreach ($times as $key => $time) { 
     $times[$key] = date('g:i:s', $time); 
  } 


      print '<pre>'. print_r($times, true).'</pre>'; 
    /* 
   * result 
   * 
    Array 
  ( 
  [0] => 9:30:00 
  [1] => 10:00:00 
  [2] => 10:30:00 
  [3] => 11:00:00 
  [4] => 11:30:00 
  [5] => 12:00:00 
  [6] => 12:30:00 
  [7] => 1:00:00 
  [8] => 1:30:00 
  [9] => 2:00:00 
  [10] => 2:30:00 
  [11] => 3:00:00 
  [12] => 3:30:00 
  [13] => 4:00:00 
   [14] => 4:30:00 
   [15] => 5:00:00 
   [16] => 5:30:00 
 ) 

  */ 

     ?>

I need to do the equivalent in JAVA code. I think this would be helpful to others.

mH16
  • 2,356
  • 4
  • 25
  • 35
  • Java is not an acronym and should not be set in all-caps. – Karl Knechtel Dec 24 '11 at 11:50
  • Use `LocalTime` and `Duration` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and it won’t be that hard (much easier than with `Calendar` and the other poorly designed and long outdated date-time classes used in most of the answers). – Ole V.V. Jul 14 '19 at 19:50

4 Answers4

5

A way to do this using only java APIs is to use the Calendar class

    Date startTime = ...//start
    Date endTime = ../end
    ArrayList<String> times = new ArrayList<String>();
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
    Calendar calendar = GregorianCalendar.getInstance();
    calendar.setTime(startTime);
    while(calendar.getTime().before(endTime)) {
         calendar.add(Calendar.MINUTE, 30);
         times.add(sdf.format(calendar.getTime()));
    }
MahdeTo
  • 11,034
  • 2
  • 27
  • 28
  • its working, but it gives complete date and time .I need like 10:00, 10:30, 11:00 etc. can you give exact format to return time as i mentioned above.My php script gives as: [0] => 9:30:00 [1] => 10:00:00 [2] => 10:30:00 [3] => 11:00:00 [4] => 11:30:00 [5] => 12:00:00 [6] => 12:30:00 – mH16 Dec 24 '11 at 17:24
  • Ok I changed it to only display the time part, try it now – MahdeTo Dec 24 '11 at 19:00
  • can you have a look at this http://stackoverflow.com/questions/8623058/how-to-set-start-time-and-end-time-with-an-interval-of-30-minutes-in-timepicker – mH16 Dec 25 '11 at 08:10
  • i need to do it with timepicker in android. – mH16 Dec 25 '11 at 08:11
  • One problem there, it does not include first value, it starts from 10:00 ,i need both inclusive means, my array should be like above php function array output – mH16 Dec 25 '11 at 10:05
  • the first value is actually included, you just need to set the start time 30 minutes before the first value or just reverse the 2 lines in the while loop – MahdeTo Dec 26 '11 at 08:19
3

I modified MahdeTo answer to include start time like this. I am posting whole code below.

enter code here






  import java.text.DateFormat;
  import java.text.SimpleDateFormat;
  import java.util.ArrayList;
  import java.util.Calendar;
  import java.util.Date;
  import java.util.GregorianCalendar;

 public class TimeRange {
    public static void main(String[] args) {        
    //
    // A string of time information
    //
    String time = "9:00:00";
    String time1 = "21:00:00";

    //
    // Create an instance of SimpleDateFormat with the specified
    // format.
    //
    DateFormat sdf1 = new SimpleDateFormat("hh:mm:ss");
    try {

        Date date = sdf1.parse(time);            
        System.out.println("Date and Time: " + date);


         Date date1 = sdf1.parse(time1);            
        System.out.println("Date and Time1: " + date1);



ArrayList<String> times = new ArrayList<String>();

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(date);

   if (calendar.getTime().before(date1)){
   times.add(sdf.format(calendar.getTime()));
  System.out.println("Initial time:  "+times);



    while(calendar.getTime().before(date1)) {

   calendar.add(Calendar.MINUTE, 30);
   times.add(sdf.format(calendar.getTime()));
   System.out.println(times);
}

 }


      } catch (Exception e) {
        e.printStackTrace();
      }
   }
}
mH16
  • 2,356
  • 4
  • 25
  • 35
2

Your best bet is probably doing this using Joda Time. It has a Duration class which you can add to a DateTime object using the .plus() method.

Take the base datetime, build your duration, cycle over it and add the datetimes into an array, just like you do (well, in fact, the code below uses a Set, since all objects will be unique).

Sample code:

public final class JodaTest
{
    private static final DateTimeFormatter FORMAT
        = DateTimeFormat.forPattern("HH:mm");

    public static void main(final String... args)
    {
        final DateTime start = FORMAT.parseDateTime("09:30");
        final DateTime end = FORMAT.parseDateTime("17:30");

        final Duration duration = Minutes.minutes(30).toStandardDuration();

        final Set<DateTime> set = new LinkedHashSet<DateTime>();

        DateTime d = new DateTime(start);

        do {
            set.add(d);
            d = d.plus(duration);
        } while (d.compareTo(end) <= 0);

        for (final DateTime dt: set)
            System.out.println(FORMAT.print(dt));

        System.exit(0);
    }
}
fge
  • 119,121
  • 33
  • 254
  • 329
1

This is the version if you have the end time the day after.

With DateTimeFormatter

    String time = "18:30-00:30";

    String startTime = time.split("-")[0];
    String endTime = time.split("-")[1];

    ArrayList<String> times = new ArrayList<>();

    LocalDate today = LocalDate.now();

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy-HH:mm");

    LocalDateTime localT0 = LocalDateTime.parse(startTime).atDate(today);

    LocalDateTime localT1 = LocalDateTime.parse(endTime).atDate(today);

    if (localT0.isAfter(localT1)){

        localT1 = localT1.plusDays(1);
    }

    while (localT0.isBefore(localT1)){

        times.add(localT0.format(dateTimeFormatter));
        localT0 = localT0.plusMinutes(30);
    }

    System.out.println(times.toString());

With SimpleDateFormat

            String time = "18:30-00:30";                    

            String startTime = time.split("-")[0];
            String endTime = time.split("-")[1];
            ArrayList<String> times = new ArrayList<>();

            Calendar calendar = Calendar.getInstance();

            Calendar calendar1 = Calendar.getInstance();

            String day = new SimpleDateFormat("dd/MM/yyyy").format(calendar.getTime());

            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy-HH:mm");
            Date time1 = null;
            Date time2 = null;

            try {
                time1 = sdf.parse(day + "-" + startTime);
                time2 = sdf.parse(day + "-" + endTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            calendar.setTime(time1);

            calendar1.setTime(time2);

            if (calendar.getTime().after(calendar1.getTime())){

               calendar1.add(Calendar.DATE, 1);

            }

            while(calendar.getTime().before(calendar1.getTime())) {
                times.add(sdf.format(calendar.getTime()));
                calendar.add(Calendar.MINUTE, 30);
            }

            System.out.println(times.toString());
Matteo Antolini
  • 2,560
  • 2
  • 19
  • 30
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Jul 14 '19 at 19:46
  • @OleV.V. You are right. Check if there is a simplest solution – Matteo Antolini Jul 15 '19 at 08:33
  • There are other ways, but possibly not simpler. I might have tried to get through without using `LocalDateTime`, but it would have involved some trickery and might have ended up harder to read. I have upvoted your answer. – Ole V.V. Jul 15 '19 at 08:55
  • Two suggestions, though: (1) Keep `LocalTime` or `LocalDateTime` objects in your list, not strings. (2) Don’t use the formatter. Declare `LocalDate today = LocalDate.now();` and then set `LocalDateTime localT0 = LocalTime.parse(startTime).atDate(today);` and similarly for `localT1`. – Ole V.V. Jul 15 '19 at 09:00