PHP Date Range Check - php

I have 2 date ranges
[contract_start_date] => 2011-10-20 [contract_end_date] => 2011-10-29
and I want to verify if the dates below are in range of the date range above
2011-05-05 and 2011-10-10
the dates given must not in any way exceed the range of the contract
Is there a function for this in PHP ?

See:: http://php.net/manual/en/datetime.diff.php
$datetime1 = new DateTime('2011-10-20');
$datetime2 = new DateTime('2011-10-29');
//PHP 5.3.0
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
//PHP 5.2.2
var_dump($datetime1 < $datetime2);
$datetime3 = new DateTime('2011-05-05');
$datetime4 = new DateTime('2011-10-10');
if ($datetime3 > $datetime1 && $datetime2 > $datetime1 && $datetime3 < $datetime2 && $datetime2 < $datetime2) {
//valid range
}//end if

$start = strtorime($contract_start_date);
$end = strtotime($contract_end_date);
$required_start = strtotime("2011-05-05");
$required_end = strtotime("2011-10-10");
if ($end > $required_end or $end < $required_start)
{
//out of range
}
if ($start < $required_start or $start > $required_end)
{
//out of range
}

This should give you exactly what you're looking for:
define(CONTRACT_START, "2011-10-20");
define(CONTRACT_END, "2011-10-29");
function checkDateRange($dateArray)
{
foreach($dateArray as $dateStr)
{
$curDate = strtotime($dateStr);
if($curDate < strtotime(CONTRACT_START) || $curDate > strtotime(CONTRACT_END))
{
return false;
}
}
return true;
}
$dates = array( 0 => "2011-10-02", 1 => "2011-10-25");
if(checkDateRange($dates))
{
echo "Dates are within range";
}
else
{
echo "Dates are NOT within range";
}

Find below code to get date difference in days, month and year:
<?php
function datediff($date1,$date2,$format='d'){
$difference = abs(strtotime($date2) - strtotime($date1));
switch (strtolower($format)){
case 'd':
$days = round((($difference/60)/60)/24,0);
break;
case 'm':
$days = round(((($difference/60)/60)/24)/30,0);
break;
case 'y':
$days = round(((($difference/60)/60)/24)/365,0);
break;
}
return $days;
}
//Example
echo datediff('2011-06-1','2010-8-30','D') . ' Days<br />';
echo datediff('2011-06-1','2010-8-30','m') . ' Months<br />';
echo datediff('2011-06-1','2010-8-30','y') . ' Years<br />';
?>

Related

How to include the startdate when create the date->diff in php

How to include the startdate as well. When you count days it omits the first day, but i want to include the first day as well.
$d1 = '2018-02-01 00:00:00';
$d2 = '2018-02-05 00:00:00';
function timeDifference($dT1, $dT2){
$d1 = new DateTime($dT1);
$d2 = new DateTime($dT2);
$d = $d1->diff($d2);
$total = $d->days;
$month = $d->m.' months';
$days = $d->d.' days';
if ($total > 30) {
$returnDate = $month.' '.$days;
}
else {
$returnDate = $days;
}
return $returnDate;
}
echo timeDifference($d1, $d2); // 4 (i want 5)
Well, the difference between the 01. and 05. is four days, it's not ignoring anything. Why don't you do it like that?
€dit: Please note that this can still go wrong for a date difference which will exceed a month (e.g. 30 days +1 = 31, but the month only has 30 days...)
<?PHP
$d1 = '2018-02-01 00:00:00';
$d2 = '2018-02-05 00:00:00';
function timeDifference($dT1, $dT2){
$d1 = new DateTime($dT1);
$d2 = new DateTime($dT2);
$d = $d1->diff($d2);
$total = $d->days;
$month = $d->m.' months';
$dayDifference = $d->d;
if($dayDifference !== 0)
{
$dayDifference++;
}
$days = $dayDifference.' days';
if ($total > 30) {
$returnDate = $month.' '.$days;
}
else {
$returnDate = $days;
}
return $returnDate;
}
echo timeDifference($d1, $d2);
?>
2:
<?PHP
$d1 = '2018-02-01 00:00:00';
$d2 = '2018-02-05 00:00:00';
function timeDifference($dT1, $dT2){
$d1 = new DateTime($dT1);
$d1->sub(new DateInterval("P1D"));
$d2 = new DateTime($dT2);
$d = $d1->diff($d2);
$total = $d->days;
$month = $d->m.' months';
$days = $d->d.' days';
if ($total > 30) {
$returnDate = $month.' '.$days;
}
else {
$returnDate = $days;
}
return $returnDate;
}
echo timeDifference($d1, $d2);
?>
The function works as expected. Between date 2018-02-01 00:00:00 and date 2018-02-05 00:00:00 there are effectively 4 days (01, 02, 03, 04). The fifth is not counted because the date 2018-02-05 00:00:00 is considered as the upper limit.
If you wish your function returns 5 instead of 4, make the increment inside it or make the right hand side input date 2018-02-06 00:00:00.

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>';

PHP: Retrieve number of days from Calendar Range Period

if
$_POST['SelectedDate1'] = 2013/08/05
and
$_POST['SelectedDate2'] = 2013/08/07
How can I set a variable which gives me back the number of days (2 in this case) to then echo it as result
I'm looking for a solution that can cover any calendar combination.
Is there any global function in php.
I think, in the following Documentation on PHP.net is exactly what you're trying to do.
http://nl3.php.net/manual/en/datetime.diff.php
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
In your case:
<?php
$first = new DateTime($_POST['SelectedDate1']);
$second = new DateTime($_POST['SelectedDate2']);
$passed = $first->diff($second);
var_dump($passed->format('%R%a days'));
For more formats, next to %R%a, see: http://nl3.php.net/manual/en/function.date.php
<?php
$days = (strtotime($_POST['SelectedDate2']) - strtotime($_POST['SelectedDate1'])) / 86400;
example:
<?php
$_POST['SelectedDate1'] = '2013/08/05' ;
$_POST['SelectedDate2'] = '2013/08/07' ;
$days = (strtotime($_POST['SelectedDate2']) - strtotime($_POST['SelectedDate1'])) / 86400;
var_export($days);
// output: 2
I use this function that I've found on this forum but I don't remember where :
function createDateRangeArray($start, $end) {
// Modified by JJ Geewax
$range = array();
if (is_string($start) === true) $start = strtotime($start);
if (is_string($end) === true ) $end = strtotime($end);
if ($start > $end) return createDateRangeArray($end, $start);
do {
$range[] = date('Y-m-d', $start);
$start = strtotime("+ 1 day", $start);
}
while($start <= $end);
return $range;
}
it returns a range of date as an array, then you just have to get the count
DateTime class is created for this:
$date1 = new DateTime('2013/08/05');
$date2 = new DateTime('2013/08/07');
$diff = $date1->diff($date2);
echo $diff->days;

PHP_comparison days between 2date

i write code in php and i get all days between 2date
function getDatesBetween2Dates($startTime, $endTime){
$day = 86400;
$format = 'Y-m-d';
$startTime = strtotime($startTime);
$endTime = strtotime($endTime);
$numDays = round(($endTime - $startTime) / $day) + 1;
$days = array();
for ($i = 0; $i < $numDays; $i++) {
$days[] = date($format, ($startTime + ($i * $day)));
}
return $days;
}
$days = getDatesBetween2Dates($_POST['periodfrom'], $_POST['periodto']);
foreach($days as $key => $value){
echo $daydatey = date('Y-m-d', strtotime($value));
//contain days between 2date from my form
}
$days2 = getDatesBetween2Dates($ppfr, $ppto);
foreach($days2 as $key2 => $value2){
echo $daydatey2 = date('Y-m-d', strtotime($value2));
}
Contain days between 2date from my DB
I just need to make comparison between $days and $days2 to check if any days in($days) exist or equal or like days in ($days2) just that. Please help.
I suggest you take a look at DateTime::diff / date_diff..
http://php.net/manual/en/datetime.diff.php (OOP)
http://php.net/manual/en/function.date-diff.php (Procedural)
This does however require php 5.3+ so ignore this answer if you are below that.
Example:
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

Undefined date_diff()

I'm trying to use date_diff():
$datetime1 = date_create('19.03.2010');
$datetime2 = date_create('22.04.2010');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%d days');
Its doesn't work for me, gives an error:
Call to undefined function date_diff()
How can I get it work?
PHP 5.2 is used.
Thanks.
The function date_diff requires a PHP version of 5.3 or greater.
UPDATE
An example for PHP 5.2 (taken from the date_diff user comments).
<?php
function date_diff($date1, $date2) {
$current = $date1;
$datetime2 = date_create($date2);
$count = 0;
while(date_create($current) < $datetime2){
$current = gmdate("Y-m-d", strtotime("+1 day", strtotime($current)));
$count++;
}
return $count;
}
echo (date_diff('2010-3-9', '2011-4-10')." days <br \>");
?>
Here is a version that doesn't use Date objects, but these are of no use anyways in 5.2.
function date_diff($d1, $d2){
$d1 = (is_string($d1) ? strtotime($d1) : $d1);
$d2 = (is_string($d2) ? strtotime($d2) : $d2);
$diff_secs = abs($d1 - $d2);
return floor($diff_secs / (3600 * 24));
}
First convert both dates to mm/dd/yyyy format then do this :
$DateDiff = floor( strtotime($datetime2 ) - strtotime( $datetime1 ) ) / 86400 ;
//this will yield the resultant difference in days
function date_diff($date1, $date2) {
$count = 0;
//Ex 2012-10-01 and 2012-10-20
if(strtotime($date1) < strtotime($date2))
{
$current = $date1;
while(strtotime($current) < strtotime($date2)){
$current = date("Y-m-d",strtotime("+1 day", strtotime($current)));
$count++;
}
}
//Ex 2012-10-20 and 2012-10-01
else if(strtotime($date2) < strtotime($date1))
{
$current = $date2;
while(strtotime($current) < strtotime($date1)){
$current = date("Y-m-d",strtotime("+1 day", strtotime($current)));
$count++;
}
$current = $current * -1;
}
return $count; }
Converting your DateTime to Unix date type, and subtracting one from another:
The format->("U") is where the DateTime is converted.
$datetime1 = date_create('19.03.2010');
$datetime2 = date_create('22.04.2010');
$intervalInDays = ($datetime2->format("U") - $datetime1->format("U"))/(3600 * 24);
Not sure if this is Y2K38 safe but it's one of the simplest date_diff workarounds.

Categories