PHP Dates and Times Generating Time Ranges - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Dates and Times Generating Time Ranges - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Monday, May 13, 2019

PHP Dates and Times Generating Time Ranges

PHP Dates and Times





Generating Time Ranges


Problem

You need to know all the days in a week or a month. For example, you want to print out a list of appointments for a week.


Solution

Use the DatePeriod class, available starting with PHP 5.3.0. Its constructor accepts a flexible combination of options that lets you control the range length, time between items in the range, and how many items there are in the range.

You can build a DatePeriod with a start, interval, and end. Here’s how to construct a
range that represents every day in August 2014:

            // Start on August 1
            $start = new DateTime('August 1, 2014');
            // End date is exclusive, so this will stop on August 31
            $end = new DateTime('September 1, 2014');
            // Go 1 day at a time
            $interval = new DateInterval('P1D');

            $range1 = new DatePeriod($start, $interval, $end);

Here’s another way to do the same thing:

            // Start on August 1
            $start = new DateTime('August 1, 2014');
            // Go 1 day at a time
            $interval= new DateInterval('P1D');
            // Recur 30 times more after the first occurrence.
            $recurrences = 30;

            $range2 = new DatePeriod($start, $interval, $recurrences);

And a third way, using the ISO 8601 specified format for describing date ranges:

            $range3 = new DatePeriod('R30/2014-08-01T00:00:00Z/P1D');

The DatePeriod class implements the Traversable interface, so once you’ve constructed an object, just pass it to foreach and you’ll get a DateTime object for each item in the range:

            foreach ($range1 as $d) {
                      print "A day in August is " . $d->format('d') . "\n";
            }

Discussion

By default a DatePeriod includes the time specified as its start and excludes the time specified as its end. You can also exclude the start time by passing DatePeriod::EXCLUDE_START_DATE as a final argument to the constructor.

DatePeriod only implements Traversable, not any of the other “make my object act like an array” interfaces that PHP provides, so you can’t grab all the values at once, for example, by passing it to implode(). You have to use foreach to accumulate the values you want into a regular array.


No comments:

Post a Comment

Post Top Ad