How to generate an array of dates with php? - php

I want to generate an array of dates between two dates with an interval of 1 hour.
Inital date: 01-01-2013 00:00:00
Final date: 02-01-2013 00:00:00
ex. of result:
[01-01-2013 00:00:00, 01-01-2013 01:00:00, 01-01-2013 02:00:00, (...), 02-01-2013 00:00:00]

Try this
$dates = array();
$start = strtotime('01-01-2013 00:00:00');
$end = strtotime('02-01-2013 00:00:00');
for($i=$start;$i<$end;$i+=3600) {
$dates[] = date('Y-m-d H:i:s',$i);
}

$start = new DateTime('2013-07-01 00:00:00', new DateTimeZone('UTC'));
$interval = new DateInterval('PT1H');
$end = new DateTime('2013-07-03 00:00:00', new DateTimeZone('UTC'));
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $date) {
$dateArray[] = $date->format('Y-m-d h:i:s');
}
var_dump($dateArray);

<?php
$start = '2013-01-01 00:00:00';
$end = '2013-01-02 00:00:00';
$dates = array();
$current = strtotime($start);
$offset = 0;
while ( $current < strtotime($end) ) {
$current = strtotime("$start +{$offset} hours");
$dates[] = date('d-m-Y H:i:s', $current);
$offset++;
}
print_r($dates);

You could try this.
$start = mktime(0,0,0,1,1,2013);
$end = mktime(0,0,0,2,1,2013);
$inc = 60*60; // 1 hour
for ($x=$start; $x<=$end; $x+$inc ) {
$dates = date('d-m-Y H:i:s, $x);
}

Related

Inserting dates within an array with PHP

I am getting the starting and ending dates from a form.
I need to put within an array all the date between the former two, including themselves.
I'm using a normal for loop and, at the same time, printing the result, to verify.
Everything appear to be alright.
But when I print_r the very array, I get only a series of equal dates. Which are all the same: last date + 1.
This is the code:
$date1 = date_create("2013-03-15");
$date2 = date_create("2013-03-22");
$diff = date_diff($date1, $date2);
echo $diff->format("%R%a days");
$diffDays = $diff->days;
echo $diffDays;
$dates = array();
$addDay = $date1;
for ($i = 0; $i < $diffDays; $i++) {
$dates[$i] = $addDay;
date_add($addDay, date_interval_create_from_date_string("1 day"));
echo "array: " . $i . " : " . date_format($dates[$i], 'Y-m-d');
}
print_r($dates);
PHP code demo
<?php
$dates = array();
$datetime1 = new DateTime("2013-03-15");
$datetime2 = new DateTime("2013-03-22");
$interval = $datetime1->diff($datetime2);
$days = (int) $interval->format('%R%a');
$currentTimestamp = $datetime1->getTimestamp();
$dates[] = date("Y-m-d H:i:s", $currentTimestamp);
for ($x = 0; $x < $days; $x++)
{
$currentTimestamp = strtotime("+1 day", $currentTimestamp);
$dates[] = date("Y-m-d H:i:s", $currentTimestamp);
}
print_r($dates);
I would do it that way
$startDate = new \DateTime("2017-03-15");
$endDate = new \DateTime("2017-03-22");
$dates = [];
$stop = false;
$date = $startDate;
while(!$stop){
$dates[] = $date->format('Y-m-d'); // or $dates[] = $date->format('Y-m-d H:i:s')
$date->modify('+1 day');
if($date->getTimestamp() > $endDate->getTimestamp()){
$stop = true;
}
}
print_r($dates);

Get month name using start date and end date?

$startDate = "2014-03-01";
$endDate= "2014-05-25";
Result required: March, April, May;
for that PHP delivers the DatePeriod object. Just have a look at the following example.
$period = new DatePeriod(
new DateTime('2014-03-01'),
DateInterval::createFromDateString('1 month'),
new DateTime('2014-05-25')
);
foreach ($period as $month) {
echo strftime('%B', $month->format('U'));
}
A quick solution is to parse each day and check it month:
$startDate = "2014-03-01";
$endDate = "2014-05-25";
$start = strtotime($startDate);
$end = strtotime($endDate);
$result = array();
while ( $start <= $end )
{
$month = date("M", $start);
if( !in_array($month, $result) )
$result[] = $month;
$start += 86400;
}
print_r($result);
I believe it can be done much efficient by new OOP (DateTime object) approach, but this is fast and no-brain if you need to make it work.
<?php
$startDate = "2014-03-01";
echo date('F',strtotime($startDate));
?
$date = date('F',strtotime($startDate));
For full month representation (ie Januaray, February, etc)
$date = date('M',strtotime($startDate));
For abbreviated...(ie Jan, Feb, Mar)
REFERENCE
If you wanna echo out those months in between based on two dates....
$d = "2014-03-01";
$startDate = new DateTime($d);
$endDate = new DateTime("2014-05-01");
function diffInMonths(DateTime $date1, DateTime $date2)
{
$diff = $date1->diff($date2);
$months = $diff->y * 12 + $diff->m + $diff->d / 30;
return (int) round($months);
}
$t = diffInMonths($startDate, $endDate);
for($i=0;$i<$t+1;$i++){
echo date('F',strtotime($d. '+'.$i.' Months'));
}
PHP SANDBOX EXAMPLE

PHP - Get start and end date of current date interval

I have as unix timestamps
$now = strtotime("2013-12-10");
$start_date = strtotime("2013-01-01");
$end_date = strtotime("2013-12-31");
The $start date and $end date span a period of time and the $now timestamp sits in the middle of the two.
I also have a variable date interval like so:
$interval = new DateInterval('P1W');
// or
$interval = new DateInterval('P3D');
Given the above how do I get the start and end timestamps of the interval that now sits in?
The $now, $start_date, $end_date and the interval will be dynamic.
Example
Lets say I have these parameters:
$start_date = '2013-01-01 00:00:00';
$end_date = '2013-12-31 23:59:59';
$now = '2013-12-10 15:45:34';
$interval = new DateInterval( 'P1W' );
I want to know the start and end date of the interval $now sits in. The output I would expect from the above params is:
$int_start_date = '2013-12-10 00:00:00';
$int_end_date = '2013-12-16 23:59:59';
I think this is a less hacky and cleaner approach than yours.
$start_date = new DateTime( '2013-01-01 00:00:00' );
$end_date = new DateTime( '2013-12-31 23:59:59' );
$end_date_ts = $end_date->getTimestamp();
$now = new DateTime( '2013-12-10 15:45:34' );
$now_ts = $now->getTimestamp();
$interval = new DateInterval( 'P1W' );
$periods = new DatePeriod( $start_date, $interval, $end_date );
/** #var \DateTime $period */
foreach($periods as $period){
$periodEnd = clone $period;
$periodEnd->add($interval);
if($period < $now && $now < $periodEnd){
$result = iterator_to_array(new \DatePeriod($period, $interval, $periodEnd->add($interval)));
$int_start_date = $result[0];
$int_end_date = $result[1];
break;
}
}
/** #var DateTime $int_start_date */
/** #var DateTime $int_end_date */
var_dump( $int_start_date->format( 'Y-m-d H:i:s' ) );
var_dump( $int_end_date->modify( '-1 Second' )->format( 'Y-m-d H:i:s' ) );
I have figured the problem myself however is hacky
$start_date = new DateTime( '2013-01-01 00:00:00' );
$end_date = new DateTime( '2013-12-31 23:59:59' );
$end_date_ts = $end_date->getTimestamp();
$now = new DateTime( '2013-12-10 15:45:34' );
$now_ts = $now->getTimestamp();
$interval = new DateInterval( 'P1W' );
$period = new DatePeriod( $start_date, $interval, $end_date );
$intervals = array();
foreach ( $period as $dt ) {
$intervals[] = $dt->getTimestamp();
}
$intervals[] = $end_date_ts;
$int_start_date = new DateTime();
$int_end_date = new DateTime();
for ( $i = 0; $i < count( $intervals ); $i++ ) {
if ( $now_ts >= $intervals[$i] && $now_ts <= $intervals[$i+1]) {
$int_start_date->setTimestamp($intervals[$i]);
$int_end_date->setTimestamp($intervals[$i+1]-1);
break;
}
}
var_dump( $int_start_date->format( 'Y-m-d H:i:s' ) );
var_dump( $int_end_date->format( 'Y-m-d H:i:s' ) );
I gladly accept better approaches if anyone has them.
You could try:
$now = time();
$interval = new DateInterval('P1W');
$interval_seconds = $interval->s + ($interval->i * 60) + ($interval->h * 60 * 60) + ($interval->d * 60 * 60 * 24);
$half_interval = round($interval_seconds / 2);
// Unix timestamps
$interval_start = $now - $half_interval;
$interval_end = $now + $half_interval;
EDIT: 2nd answer following on from comments
This only works for intervals of length 1 - eg 1 week, 1 year etc.
If your interval is > 1 then you'll need to somehow determine how far through the interval you are... e.g for a 2 week interval, are you in the first week or the second week?
$now = time();
$interval = "week";
switch ($interval) {
case "year":
$start_int = strtotime(date("Y", $now)."-01-01 00:00:00");
$end_int = strtotime(date("Y", $now)."-12-31 23:59:59");
break;
case "month":
$start_int = strtotime(date("Y-m", $now)."-01 00:00:00");
$end_int = strtotime(date("Y-m-t", $now)." 23:59:59");
break;
case "week":
$start_week = date("Y-m-d", strtotime("previous Monday", $now));
$end_week = date("Y-m-d", strtotime("next Sunday", $now));
$start_int = strtotime($start_week." 00:00:00");
$end_int = strtotime($end_week." 23:59:59");
break;
case "day":
$start_int = strtotime(date("Y-m-d", $now)." 00:00:00");
$end_int = strtotime(date("Y-m-d", $now)." 23:59:59");
break;
case "hour":
$start_int = strtotime(date("Y-m-d H", $now).":00:00");
$end_int = strtotime(date("Y-m-d H", $now).":59:59");
break;
case "minute":
$start_int = strtotime(date("Y-m-d H:i", $now).":00");
$end_int = strtotime(date("Y-m-d H:i", $now).":59");
break;
}
echo date("Y-m-d H:i:s", $start_int), "<br>";
echo date("Y-m-d H:i:s", $end_int), "<br>";
Update 3
I've put the logic from your answer into a single loop:
$start_date = new DateTime( '2013-01-01 00:00:00' );
$end_date = new DateTime( '2013-12-31 23:59:59' );
$end_date_ts = $end_date->getTimestamp();
$now = new DateTime( '2013-12-10 15:45:34' );
$now_ts = $now->getTimestamp();
$interval = new DateInterval( 'P1W' );
$period = new DatePeriod( $start_date, $interval, $end_date );
$int_start_date = $start_date;
$int_end_date = $end_date;
foreach ( $period as $dt ) {
$timestamp = $dt->getTimestamp();
if ($now_ts >= $timestamp) {
$int_start_date->setTimestamp($timestamp);
}
if ($now_ts < $timestamp and $timestamp < $int_end_date->getTimestamp()) {
$int_end_date->setTimestamp($timestamp - 1);
}
}
var_dump( $int_start_date->format( 'Y-m-d H:i:s' ) );
var_dump( $int_end_date->format( 'Y-m-d H:i:s' ) );

PHP: List of days between two dates [duplicate]

This question already has answers here:
PHP: Return all dates between two dates in an array [duplicate]
(26 answers)
Closed 4 years ago.
Is there an easy way to get a list of days between two dates in PHP?
I would like to have something like this in the end:
(pseudocode)
date1 = 29/08/2013
date2 = 03/09/2013
resultArray = functionReturnDates(date1, date2);
and the resulting array would contain:
resultArray[0] = 29/08/2013
resultArray[1] = 30/08/2013
resultArray[2] = 31/08/2013
resultArray[3] = 01/09/2013
resultArray[4] = 02/09/2013
resultArray[5] = 03/09/2013
for example.
$date1 = '29/08/2013';
$date2 = '03/09/2013';
function returnDates($fromdate, $todate) {
$fromdate = \DateTime::createFromFormat('d/m/Y', $fromdate);
$todate = \DateTime::createFromFormat('d/m/Y', $todate);
return new \DatePeriod(
$fromdate,
new \DateInterval('P1D'),
$todate->modify('+1 day')
);
}
$datePeriod = returnDates($date1, $date2);
foreach($datePeriod as $date) {
echo $date->format('d/m/Y'), PHP_EOL;
}
function DatePeriod_start_end($begin,$end){
$begin = new DateTime($begin);
$end = new DateTime($end.' +1 day');
$daterange = new DatePeriod($begin, new DateInterval('P1D'), $end);
foreach($daterange as $date){
$dates[] = $date->format("Y-m-d");
}
return $dates;
}
dunno if this is at all practical, but it works pretty straight-forward
$end = '2013-08-29';
$start = '2013-08-25';
$datediff = strtotime($end) - strtotime($start);
$datediff = floor($datediff/(60*60*24));
for($i = 0; $i < $datediff + 1; $i++){
echo date("Y-m-d", strtotime($start . ' + ' . $i . 'day')) . "<br>";
}
Try this:
function daysBetween($start, $end)
$dates = array();
while($start <= $end)
{
array_push(
$dates,
date(
'dS M Y',
$start
)
);
$start += 86400;
}
return $dates;
}
$start = strtotime('2009-10-20');
$end = strtotime('2009-10-25');
var_dump(daysBetween($start,$end));
$datearray = array();
$date = $date1;
$days = ceil(abs($date2 - $date1) / 86400) + 1;//no of days
for($i = 1;$i <= $days; $i++){
array_push($datearray,$date);
$date = $date+86400;
}
foreach($datearray as $days){
echo date('Y-m-d, $days);
}

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

I'm starting with a date 2010-05-01 and ending with 2010-05-10. How can I iterate through all of those dates in PHP?
$begin = new DateTime('2010-05-01');
$end = new DateTime('2010-05-10');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("l Y-m-d H:i:s\n");
}
This will output all days in the defined period between $start and $end. If you want to include the 10th, set $end to 11th. You can adjust format to your liking. See the PHP Manual for DatePeriod. It requires PHP 5.3.
This also includes the last date
$begin = new DateTime( "2015-07-03" );
$end = new DateTime( "2015-07-09" );
for($i = $begin; $i <= $end; $i->modify('+1 day')){
echo $i->format("Y-m-d");
}
If you dont need the last date just remove = from the condition.
Converting to unix timestamps makes doing date math easier in php:
$startTime = strtotime( '2010-05-01 12:00' );
$endTime = strtotime( '2010-05-10 12:00' );
// Loop between timestamps, 24 hours at a time
for ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) {
$thisDate = date( 'Y-m-d', $i ); // 2010-05-01, 2010-05-02, etc
}
When using PHP with a timezone having DST, make sure to add a time that is not 23:00, 00:00 or 1:00 to protect against days skipping or repeating.
Copy from php.net sample for inclusive range:
$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2012-08-31' );
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach($daterange as $date){
echo $date->format("Ymd") . "<br>";
}
Here is another simple implementation -
/**
* Date range
*
* #param $first
* #param $last
* #param string $step
* #param string $format
* #return array
*/
function dateRange( $first, $last, $step = '+1 day', $format = 'Y-m-d' ) {
$dates = [];
$current = strtotime( $first );
$last = strtotime( $last );
while( $current <= $last ) {
$dates[] = date( $format, $current );
$current = strtotime( $step, $current );
}
return $dates;
}
Example:
print_r( dateRange( '2010-07-26', '2010-08-05') );
Array (
[0] => 2010-07-26
[1] => 2010-07-27
[2] => 2010-07-28
[3] => 2010-07-29
[4] => 2010-07-30
[5] => 2010-07-31
[6] => 2010-08-01
[7] => 2010-08-02
[8] => 2010-08-03
[9] => 2010-08-04
[10] => 2010-08-05
)
$startTime = strtotime('2010-05-01');
$endTime = strtotime('2010-05-10');
// Loop between timestamps, 1 day at a time
$i = 1;
do {
$newTime = strtotime('+'.$i++.' days',$startTime);
echo $newTime;
} while ($newTime < $endTime);
or
$startTime = strtotime('2010-05-01');
$endTime = strtotime('2010-05-10');
// Loop between timestamps, 1 day at a time
do {
$startTime = strtotime('+1 day',$startTime);
echo $startTime;
} while ($startTime < $endTime);
User this function:-
function dateRange($first, $last, $step = '+1 day', $format = 'Y-m-d' ) {
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while( $current <= $last ) {
$dates[] = date($format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
Usage / function call:-
Increase by one day:-
dateRange($start, $end); //increment is set to 1 day.
Increase by Month:-
dateRange($start, $end, "+1 month");//increase by one month
use third parameter if you like to set date format:-
dateRange($start, $end, "+1 month", "Y-m-d H:i:s");//increase by one month and format is mysql datetime
For Carbon users
use Carbon\Carbon;
$startDay = Carbon::parse("2021-08-01");
$endDay= Carbon::parse("2021-08-05");
$period = $startDay->range($endDay, 1, 'day');
When I print the data
[
Carbon\Carbon #1627790400 {#4970
date: 2021-08-01 00:00:00.0 America/Toronto (-04:00),
},
Carbon\Carbon #1627876800 {#4974
date: 2021-08-02 00:00:00.0 America/Toronto (-04:00),
},
Carbon\Carbon #1627963200 {#4978
date: 2021-08-03 00:00:00.0 America/Toronto (-04:00),
},
Carbon\Carbon #1628049600 {#5007
date: 2021-08-04 00:00:00.0 America/Toronto (-04:00),
},
Carbon\Carbon #1628136000 {#5009
date: 2021-08-05 00:00:00.0 America/Toronto (-04:00),
},
]
This is Laravel data dump using dd($period->toArray());. You can now iterate through $period if you want with a foreach statement.
One important note - it includes both the edge dates provided to method.
For more cool date related stuff, do check out the Carbon docs.
here's a way:
$date = new Carbon();
$dtStart = $date->startOfMonth();
$dtEnd = $dtStart->copy()->endOfMonth();
$weekendsInMoth = [];
while ($dtStart->diffInDays($dtEnd)) {
if($dtStart->isWeekend()) {
$weekendsInMoth[] = $dtStart->copy();
}
$dtStart->addDay();
}
The result of $weekendsInMoth is array of weekend days!
If you're using php version less than 8.2 and don't have the DatePeriod::INCLUDE_END_DATE const. I wrote a method that returns an array of \DateTimeImmutable.
This works with a start date before, the same or after the end date.
/**
* #param DateTimeImmutable $start
* #param DateTimeImmutable $end
* #return array<\DateTimeImmutable>
*/
public static function getRangeDays(\DateTimeImmutable $start, \DateTimeImmutable $end): array
{
$startDate = $start;
$endDate = $end;
$forwards = $endDate >= $startDate;
$carryDate = $startDate;
$days = [];
while (true) {
if (($forwards && $carryDate > $end) || (!$forwards && $carryDate < $end)) {
break;
}
$days[] = $carryDate;
if ($forwards) {
$carryDate = $carryDate->modify('+1 day');
} else {
$carryDate = $carryDate->modify('- 1 day');
}
}
return $days;
}
$date = new DateTime($_POST['date']);
$endDate = date_add(new DateTime($_POST['date']),date_interval_create_from_date_string("7 days"));
while ($date <= $endDate) {
print date_format($date,'d-m-Y')." AND END DATE IS : ".date_format($endDate,'d-m-Y')."\n";
date_add($date,date_interval_create_from_date_string("1 days"));
}
You can iterate like this also, The $_POST['date'] can be dent from your app or website
Instead of $_POST['date'] you can also place your string here "21-12-2019". Both will work.
<?php
$start_date = '2015-01-01';
$end_date = '2015-06-30';
while (strtotime($start_date) <= strtotime($end_date)) {
echo "$start_daten";
$start_date = date ("Y-m-d", strtotime("+1 days", strtotime($start_date)));
}
?>
If you use Laravel and want to use Carbon the correct solution would be the following:
$start_date = Carbon::createFromFormat('Y-m-d', '2020-01-01');
$end_date = Carbon::createFromFormat('Y-m-d', '2020-01-31');
$period = new CarbonPeriod($start_date, '1 day', $end_date);
foreach ($period as $dt) {
echo $dt->format("l Y-m-d H:i:s\n");
}
Remember to add:
use Carbon\Carbon;
use Carbon\CarbonPeriod;

Categories