Php datetime in range

Как получить все дни между датами в PHP

Несколько примеров как найти все дни в промежутке между двумя датами в виде значения и списка.

Количество дней между датами

$date_1 = '28.03.2022 00:00'; $date_2 = '02.04.2022 23:59'; $seconds = abs(strtotime($date_1) - strtotime($date_2)); echo round($seconds / 86400, 1); // 6
$date_1 = '28.03.2022 00:00'; $date_2 = '02.04.2022 18:00'; $seconds = abs(strtotime($date_1) - strtotime($date_2)); echo round($seconds / 86400, 1); // 5.6

Формирование массива, содержащий все дни из интервала

Первый способ – использование классов DatePeriod, DateTime и DateInterval (доступны с версии PHP 5.3).

* Если в конечной дате не указать время (23:59), то в результирующем массиве не будет последнего дня.

$period = new DatePeriod( new DateTime('28.03.2022'), new DateInterval('P1D'), new DateTime('02.04.2022 23:59') ); $dates = array(); foreach ($period as $key => $value) < $dates[] = $value->format('d.m.Y'); > print_r($dates);

Результат:

Array ( [0] => 28.03.2022 [1] => 29.03.2022 [2] => 30.03.2022 [3] => 31.03.2022 [4] => 01.04.2022 [5] => 02.04.2022 )

Функция на основе strtotime

function get_dates($start, $end, $format = 'd.m.Y') < $day = 86400; $start = strtotime($start . ' -1 days'); $end = strtotime($end . ' +1 days'); $nums = round(($end - $start) / $day); $days = array(); for ($i = 1; $i < $nums; $i++) < $days[] = date($format, ($start + ($i * $day))); >return $days; > $dates = get_dates('28.03.2022', '02.04.2022'); print_r($dates);

Результат:

Array ( [0] => 28.03.2022 [1] => 29.03.2022 [2] => 30.03.2022 [3] => 31.03.2022 [4] => 01.04.2022 [5] => 02.04.2022 )

Источник

The DatePeriod class

A date period allows iteration over a set of dates and times, recurring at regular intervals, over a given period.

Class synopsis

Predefined Constants

DatePeriod::INCLUDE_END_DATE

Properties

The minimum amount of instances as retured by the iterator.

If the number of recurrences has been explicitly passed through the recurrences parameter in the constructor of the DatePeriod instance, then this property contains this value, plus one if the start date has not been disabled through DatePeriod::EXCLUDE_START_DATE , plus one if the end date has been enabled through DatePeriod::INCLUDE_END_DATE .

If the number of recurrences has not been explicitly passed, then this property contains the minimum number of returned instances. This would be 0 , plus one if the start date has not been disabled through DatePeriod::EXCLUDE_START_DATE , plus one if the end date has been enabled through DatePeriod::INCLUDE_END_DATE .

$start = new DateTime ( ‘2018-12-31 00:00:00’ );
$end = new DateTime ( ‘2021-12-31 00:00:00’ );
$interval = new DateInterval ( ‘P1M’ );
$recurrences = 5 ;

// recurrences explicitly set through the constructor
$period = new DatePeriod ( $start , $interval , $recurrences , DatePeriod :: EXCLUDE_START_DATE );
echo $period -> recurrences , «\n» ;

$period = new DatePeriod ( $start , $interval , $recurrences );
echo $period -> recurrences , «\n» ;

Читайте также:  Html код для оставить комментарий

$period = new DatePeriod ( $start , $interval , $recurrences , DatePeriod :: INCLUDE_END_DATE );
echo $period -> recurrences , «\n» ;

// recurrences not set in the constructor
$period = new DatePeriod ( $start , $interval , $end );
echo $period -> recurrences , «\n» ;

$period = new DatePeriod ( $start , $interval , $end , DatePeriod :: EXCLUDE_START_DATE );
echo $period -> recurrences , «\n» ;
?>

The above example will output:

Whether to include the end date in the set of recurring dates or not.

Whether to include the start date in the set of recurring dates or not.

The start date of the period.

During iteration this will contain the current date within the period.

The end date of the period.

An ISO 8601 repeating interval specification.

Changelog

Version Description
8.2.0 The DatePeriod::INCLUDE_END_DATE constant and include_end_date property have been added.
8.0.0 DatePeriod implements IteratorAggregate now. Previously, Traversable was implemented instead.

Table of Contents

  • DatePeriod::__construct — Creates a new DatePeriod object
  • DatePeriod::getDateInterval — Gets the interval
  • DatePeriod::getEndDate — Gets the end date
  • DatePeriod::getRecurrences — Gets the number of recurrences
  • DatePeriod::getStartDate — Gets the start date

Источник

How To Create Date Range In PHP (Simple Examples)

Welcome to a quick tutorial on how to create a date range in PHP. Need to loop through a range of dates, or generate date intervals?

  1. Using DateTime, DateInterval , and DatePeriod objects.
    • $start = new DateTime(«2020-01-01»);
    • $end = new DateTime(«2020-02-02»);
    • $interval = new DateInterval(«P1D»);
    • $range = new DatePeriod($start, $interval, $end);
    • foreach ($range as $d) < echo $d->format(«Y-m-d»); >
  2. Using Unix Timestamps.
    • $start = strtotime(«2020-01-01»);
    • $end = strtotime(«2020-02-01»);
    • for (let $i=$start; $i

That should cover the basics, but let us walk through more examples in this guide – Read on!

TLDR – QUICK SLIDES

Create Date Range In PHP

TABLE OF CONTENTS

PHP DATE RANGE

All right, let us now walk through the examples on how to create a date range in PHP.

1) USING DATE-TIME OBJECTS

"; $interval = new DateInterval("P1D"); $range = new DatePeriod($start, $interval, $end); foreach ($range as $date) < echo $date->format("Y-m-d") . "
"; > // (C) WEEKLY INTERVAL - CAPTAIN OBVIOUS P7D echo "WEEKLY
"; $interval = new DateInterval("P7D"); $range = new DatePeriod($start, $interval, $end); foreach ($range as $date) < echo $date->format("Y-m-d") . "
"; > // (D) MONTHLY INTERVAL echo "MONTHLY
"; $interval = new DateInterval("P1M"); $range = new DatePeriod($start, $interval, $end); foreach ($range as $date) < echo $date->format("Y-m-d") . "
"; >
  • First, define the start and end dates –
    • $start = new DateTime(«YYYY-MM-DD»)
    • $end = new DateTime(«YYYY-MM-DD»)
    • PXD Intervals of X days.
    • PXM Intervals of X months.
    • PXY Intervals of X years.

    P.S. The intervals can go down to even hours, minutes, and seconds. Will leave a link in the extras section below to the PHP manual.

    2) USING UNIX TIMESTAMPS

    "; for ($i=$start; $i"; > // (C) WEEKLY INTERVAL (1 DAY = 604800 SECONDS) echo "WEEKLY
    "; for ($i=$start; $i"; > // (D) MONTHLY INTERVAL echo "MONTHLY
    "; $i = $start; while ($i < $end) < $idate = date("Y-m-d", $i); echo $idate."
    "; $i = strtotime($idate . "+1 month"); >
    • First, get the Unix Timestamps for the start and end dates.
      • $start = strtotime(«YYYY-MM-DD»)
      • $end = strtotime(«YYYY-MM-DD»)
      • 1 day has 86400 seconds, so for a daily range – for ($i=$start; $i
      • 1 week has 604800 seconds, so for a weekly range – for ($i=$start; $i
      • Take note of the monthly range though, not all months have exactly 30 days. So the safest way to loop is to use strtotime(«YYYY-MM-DD +1 MONTH») to calculate the exact “timestamp for the next months”.

      DOWNLOAD & NOTES

      Here is the download link to the example code, so you don’t have to copy-paste everything.

      SUPPORT

      600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

      EXAMPLE CODE DOWNLOAD

      Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

      That’s all for the main tutorial, and here is a small section on some extras and links that may be useful to you.

      INFOGRAPHIC CHEAT SHEET

      THE END

      Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

      Leave a Comment Cancel Reply

      Breakthrough Javascript

      Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

      Socials

      About Me

      W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

      Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

      Источник

      Php datetime in range

      • Different ways to write a PHP code
      • How to write comments in PHP ?
      • Introduction to Codeignitor (PHP)
      • How to echo HTML in PHP ?
      • Error handling in PHP
      • How to show All Errors in PHP ?
      • How to Start and Stop a Timer in PHP ?
      • How to create default function parameter in PHP?
      • How to check if mod_rewrite is enabled in PHP ?
      • Web Scraping in PHP Using Simple HTML DOM Parser
      • How to pass form variables from one page to other page in PHP ?
      • How to display logged in user information in PHP ?
      • How to find out where a function is defined using PHP ?
      • How to Get $_POST from multiple check-boxes ?
      • How to Secure hash and salt for PHP passwords ?
      • Program to Insert new item in array on any position in PHP
      • PHP append one array to another
      • How to delete an Element From an Array in PHP ?
      • How to print all the values of an array in PHP ?
      • How to perform Array Delete by Value Not Key in PHP ?
      • Removing Array Element and Re-Indexing in PHP
      • How to count all array elements in PHP ?
      • How to insert an item at the beginning of an array in PHP ?
      • PHP Check if two arrays contain same elements
      • Merge two arrays keeping original keys in PHP
      • PHP program to find the maximum and the minimum in array
      • How to check a key exists in an array in PHP ?
      • PHP | Second most frequent element in an array
      • Sort array of objects by object fields in PHP
      • PHP | Sort array of strings in natural and standard orders
      • How to pass PHP Variables by reference ?
      • How to format Phone Numbers in PHP ?
      • How to use php serialize() and unserialize() Function
      • Implementing callback in PHP
      • PHP | Merging two or more arrays using array_merge()
      • PHP program to print an arithmetic progression series using inbuilt functions
      • How to prevent SQL Injection in PHP ?
      • How to extract the user name from the email ID using PHP ?
      • How to count rows in MySQL table in PHP ?
      • How to parse a CSV File in PHP ?
      • How to generate simple random password from a given string using PHP ?
      • How to upload images in MySQL using PHP PDO ?
      • How to check foreach Loop Key Value in PHP ?
      • How to properly Format a Number With Leading Zeros in PHP ?
      • How to get a File Extension in PHP ?
      • How to get the current Date and Time in PHP ?
      • PHP program to change date format
      • How to convert DateTime to String using PHP ?
      • How to get Time Difference in Minutes in PHP ?
      • Return all dates between two dates in an array in PHP
      • Sort an array of dates in PHP
      • How to get the time of the last modification of the current page in PHP?
      • How to convert a Date into Timestamp using PHP ?
      • How to add 24 hours to a unix timestamp in php?
      • Sort a multidimensional array by date element in PHP
      • Convert timestamp to readable date/time in PHP
      • PHP | Number of week days between two dates
      • PHP | Converting string to Date and DateTime
      • How to get last day of a month from date in PHP ?
      • PHP | Change strings in an array to uppercase
      • How to convert first character of all the words uppercase using PHP ?
      • How to get the last character of a string in PHP ?
      • How to convert uppercase string to lowercase using PHP ?
      • How to extract Numbers From a String in PHP ?
      • How to replace String in PHP ?
      • How to Encrypt and Decrypt a PHP String ?
      • How to display string values within a table using PHP ?
      • How to write Multi-Line Strings in PHP ?
      • How to check if a String Contains a Substring in PHP ?
      • How to append a string in PHP ?
      • How to remove white spaces only beginning/end of a string using PHP ?
      • How to Remove Special Character from String in PHP ?
      • How to create a string by joining the array elements using PHP ?
      • How to prepend a string in PHP ?

      Источник

Оцените статью