PHP: Retrieve number of days from Calendar Range Period - php

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;

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

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

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_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