php check multiple dates in array are within a date range - php

I have an array structured like this:
Array ( [0] => 24-12-2013 [1] => 25-12-2013 [2] => 26-12-2014 [3] => 27-12-2013 [4])
I would like to check if any of the dates in the array are within a given date range.
The date range is structured like this:
$start = (date("d-m-Y", strtotime('25-12-2013')));
$end = (date("d-m-Y", strtotime('26'12'2013')));
I would like to know which dates in the array are within the date range.

Couple things:
Use timestamps or DateTime objects to compare dates, not strings
Use date format YYYY-MM-DD to avoid potential ambiguity about your date format (d/m/y or m/d/y)
This code will do what you want:
$dates = array("2013-12-24","2013-12-25","2014-12-24","2013-12-27");
$start = strtotime('2013-12-25');
$end = strtotime('2013-12-26');
foreach($dates AS $date) {
$timestamp = strtotime($date);
if($timestamp >= $start && $timestamp <= $end) {
echo "The date $date is within our date range\n";
} else {
echo "The date $date is NOT within our date range\n";
}
}
See it in action:
http://3v4l.org/GWJI2

$dates = array ('24-12-2013', '25-12-2013', '26-12-2014', '27-12-2013');
$start = strtotime('25-12-2013');
$end = strtotime('26-12-2013');
$inDateRange = count(
array_filter(
$dates,
function($value) use($start, $end) {
$value = strtotime($value);
return ($value >= $start && $value <= $end);
}
)
);

<?php
$start = DateTime::createFromFormat('d-m-Y', '25-12-2013');
$end = DateTime::createFromFormat('d-m-Y', '26-12-2013');
$dates = array('24-12-2013','25-12-2013','26-12-2014','27-12-2013');
$matches = array();
foreach ($dates as $date) {
$date2 = DateTime::createFromFormat('d-m-Y', $date);
if ($date2 >= $start && $date2 =< $end) {
$matches[] = $date;
}
}
print_r($matches);
See it in action

$_between = array();
$start = date('Ymd', strtotime($start));
$end = date('Ymd', strtotime($end));
foreach ($dates as $date)
{
$date = date('Ymd',strtotime($date));
if ($date > $start && $date < $end) {
array_push($_between,$date);
continue;
}
}
echo '<pre>';
var_dump($_between);
echo '</pre>';

Loop over the array turning each date into unix time (seconds since Jan 1, 1970), and do simple math to see if the number of seconds is between the range. Like so:
$start = strtotime('25-12-2013');
$end = strtotime('26'12'2013');
foreach($date in $dates) {
$unix_time = strtotime($date);
if($unix_time > $start && $unix_time < $end)
//in range
}

// PHP >= 5.3:
$dates_in_range = array_filter($array, function($date) {
global $start;
global $end;
return (strtotime($date) >= strtotime($start) and strtotime($date) <= strtotime($end));
});

Related

foreach array in SQL, print as json [duplicate]

I want to run a while(or any) loop to output a small list of dates as an array
$start = $day = strtotime("-1 day");
$end = strtotime('+6 day');
while($day < $end)
{
echo date('d-M-Y', $day) .'<br />';
$day = strtotime("+1 day", $day) ;
}
This works fine for printing, but I want to save it as an array (and insert it in a mysql db).
Yes! I don't know what I'm doing.
to create a array, you need to first initialize it outside your loop (because of variable scoping)
$start = $day = strtotime("-1 day");
$end = strtotime('+6 day');
$dates = array(); //added
while($day < $end)
{
$dates[] = date('d-M-Y', $day); // modified
$day = strtotime("+1 day", $day) ;
}
echo "<pre>";
var_dump($dates);
echo "</pre>";
you can then use your dates using either foreach or while
foreach approach :
foreach($dates as $date){
echo $date."<br>";
}
while approach :
$max = count($dates);
$i = 0;
while($i < $max){
echo $dates[$i]."<br>";
}
$arr = Array();
while(...) {
$arr[] = "next element";
...
}
The [] adds a new element to an array, just like push() but without the overhead of calling a function.
The simple way is just:
$start = $day = strtotime("-1 day");
$end = strtotime('+6 day');
$arr = array();
while($day < $end)
{
$arr[] = date('d-M-Y', $day);
$day = strtotime("+1 day", $day) ;
}
// Do stuff with $arr
the $arr[] = $var is the syntax for appending to an array in PHP. Arrays in php do not have a fixed size and therefore can be appended to easily.

how to get sunday date between two date

I try this
<?php
$startdate = '2016-07-15';
$enddate = '2016-07-17';
$sundays = [];
$startweek=date("W",strtotime($startdate));
$endweek=date("W",strtotime($enddate));
$year=date("Y",strtotime($startdate));
for($i=$startweek;$i<=$endweek;$i++) {
$result=$this->getWeek($i,$year);
if($result>$startdate && $result<$enddate) {
$sundays[] = $result;
}
}
print_r($sundays);
public function getWeek($week, $year)
{
$dto = new \DateTime();
$result = $dto->setISODate($year, $week, 0)->format('Y-m-d');
return $result;
}
?>
this return blank array. but in between two dates 2016-07-17 is Sunday.
I get output as 2016-07-17
I refer this here
But in this link return output as no of sunday not date.
Give this a try:
$startDate = new DateTime('2016-07-15');
$endDate = new DateTime('2016-07-17');
$sundays = array();
while ($startDate <= $endDate) {
if ($startDate->format('w') == 0) {
$sundays[] = $startDate->format('Y-m-d');
}
$startDate->modify('+1 day');
}
var_dump($sundays);
If you want later to use the DateTime objects instead of the formatted date, then you must use DateTimeImmutable for the $startDate variable:
$startDate = new DateTimeImmutable('2016-07-15');
$endDate = new DateTimeImmutable('2016-07-17');
$sundays = array();
while ($startDate <= $endDate) {
if ($startDate->format('w') == 0) {
$sundays[] = $startDate;
}
$startDate->modify('+1 day');
}
var_dump($sundays);
function getDateForSpecificDayBetweenDates($startDate, $endDate, $weekdayNumber)
{
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
$dateArr = array();
do
{
if(date("w", $startDate) != $weekdayNumber)
{
$startDate += (24 * 3600); // add 1 day
}
} while(date("w", $startDate) != $weekdayNumber);
while($startDate <= $endDate)
{
$dateArr[] = date('Y-m-d', $startDate);
$startDate += (7 * 24 * 3600); // add 7 days
}
return($dateArr);
}
$dateArr = getDateForSpecificDayBetweenDates('2010-01-01', '2010-12-31', 0);
print "<pre>";
print_r($dateArr);
Try out this code..
Try this
$start = new DateTime($startDate);
$end = new DateTime($endDate);
$sundays = [];
while ($start->getTimestamp() != $end->getTimestamp()) {
if ($start->format('w') == 0) {
$sundays[] = $start->format('Y-m-d');
}
$start->add('+1 DAY');
}
This will return you all sundays between two dates.
$startdate = '2016-05-1';
$enddate = '2016-05-20';
function getSundays($start, $end) {
$timestamp1 = strtotime($start);
$timestamp2 = strtotime($end);
$sundays = array();
$oneDay = 60*60*24;
for($i = $timestamp1; $i <= $timestamp2; $i += $oneDay) {
$day = date('N', $i);
// If sunday
if($day == 7) {
// Save sunday in format YYYY-MM-DD, if you need just timestamp
// save only $i
$sundays[] = date('Y-m-d', $i);
// Since we know it is sunday, we can simply skip
// next 6 days so we get right to next sunday
$i += 6 * $oneDay;
}
}
return $sundays;
}
var_dump(getSundays($startdate, $enddate));
Use Carbon
$arrayOfDate = [];
$startDate = Carbon::parse($startDate)->modify('this sunday');
$endDate = Carbon::parse($endDate);
for ($date = $startDate; $date->lte($endDate); $date->addWeek()) {
$arrayOfDate[] = $date->format('Y-m-d');
}
return $arrayOfDate;

How can I calculate date weekend in php

I have a date like this
$start = strtotime('2010-01-01'); $end = strtotime('2010-01-25');
My question:
How can I calculate or count weekend from $start & $end date range..??
A more modern approach is using php's DateTime class. Below, you get an array with week numbers as keys. I added the counts of weeks and weekend days.
<?php
$begin = new DateTime('2010-01-01');
$end = new DateTime('2010-01-25');
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval, $end);
$weekends = [];
foreach($daterange as $date) {
if (in_array($date->format('N'), [6,7])) {
$weekends[$date->format('W')][] = $date->format('Y-m-d');
}
}
print_r($weekends);
echo 'Number of weeks: ' . count($weekends);
echo 'Number of weekend days: ' . (count($weekends, COUNT_RECURSIVE) - count($weekends));
Note: if you're using PHP 5.3, use array() instead of block arrays [].
May be this code snippet will help:
<?php
//get current month for example
$beginday = date("Y-m-01");
$lastday = date("Y-m-t");
$nr_work_days = getWorkingDays($beginday, $lastday);
echo $nr_work_days;
function getWorkingDays($startDate, $endDate)
{
$begin = strtotime($startDate);
$end = strtotime($endDate);
if ($begin > $end) {
echo "startdate is in the future! <br />";
return 0;
} else {
$no_days = 0;
$weekends = 0;
while ($begin <= $end) {
$no_days++; // no of days in the given interval
$what_day = date("N", $begin);
if ($what_day > 5) { // 6 and 7 are weekend days
$weekends++;
};
$begin += 86400; // +1 day
};
$working_days = $no_days - $weekends;
return $working_days;
}
}
Another solution can be: (Get date range between two dates excluding weekends)
This might help maybe:
$start = strtotime('2010-01-01');
$end = strtotime('2010-01-25');
$differ = $end-$start;
$min = $differ/60;
$hrs = $min/60;
$days = $hrs/24;
$weeks = $days/7;
if(is_int($weeks))
$weeks++;
echo '<pre>';
print_r(ceil($weeks));
echo '</pre>';

Want Current Months All Date in PHP

i have a Date array like this
$dateArray = array('2012-04-11','2012-04-29','2012-04-26','2012-04-23','2012-03-21','2012-07-23','2012-12-19','2012-04-27','2012-05-12','2012-05-27','2012-05-28');
and i m using code to filter this array is
but it's not working
$start_date= date('Y-m-d',strtotime('first day of this month')) ;
$end_date =date('Y-m-d',strtotime('first day of next month')) ;
$month = array();
foreach ($dateArray as $dates)
{
$dateTimes = strtotime($dates);
if (($start_date >= $dateTimes) && ($end_date <= $dateTimes))
{
$month[]= $dates;
}
}
var_dump($month);
but it's not working
You need to compare unix timestamps to do the comparison properly:
$dateArray = array('2012-04-11','2012-04-29','2012-04-26','2012-04-23','2012-03-21','2012-07-23','2012-12-19','2012-04-27','2012-05-12','2012-05-27','2012-05-28');
$start_date = strtotime('first day of this month') ;
$end_date = strtotime('first day of next month') ;
$month = array();
foreach ($dateArray as $dates)
{
$dateTimes = strtotime($dates);
if (($start_date >= $dateTimes) && ($end_date <= $dateTimes))
{
$month[]= $dates;
}
}
var_dump($month);
Hi If you want to show only dates from array having current month then
foreach($dateArray AS $dateArr){
if(date('M') == date('M' , strtotime($dateArr))){
echo $mnthDate[] = $dateArr;echo "<br/>";
}
}
Else if also want to check both year and month same as current year and month the.
foreach($dateArray AS $dateArr){
if((date('M') == date('M' , strtotime($dateArr))) && (date('Y') == date('Y' , strtotime($dateArr)))){
$yrDate[] = $dateArr;echo "<br/>";
}
}

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