I try to write a script that can calculate the difference between two dates, in days, and the diff does not behave as I need to.
More specific, lets say we have the following two date/times:
2015-03-18 23:00
2015-03-19 02:00
The actual time difference is four hours, and in this terms the diff works fine !
But what I like to know is, if the calendar date has been change, and what is the actual difference.
So in the example above, the calendar dates having 1 day difference.
In the following example
2015-03-18 23:00
2015-03-21 02:00
I have three days difference. So how can I calculate this date difference ?
At the moment I use the following code:
$datetime1 = new DateTime('2009-10-11 23:30');
$datetime2 = new DateTime('2009-10-12 02:30');
$interval = $datetime1->diff($datetime2);
echo "<pre>";
print_r($interval);
echo "</pre>";
and the result is the following:
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 3
[i] => 0
[s] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 0
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
Is there any idea ? Thanks ...
A really simple solution
Notice: this will only work if the days are in the same month.
$datetime1 = new DateTime('2015-03-18 23:00');
$datetime2 = new DateTime('2015-03-21 02:00');
$difference = $datetime2->format('d') - $datetime1->format('d'); //3
Clean solution
You could remove everything from the date, but the year, month and day and use diff() as you already did.
$datetime1 = new DateTime('2015-03-18 23:00');
$datetime2 = new DateTime('2015-03-21 02:00');
$datetime1modified = new DateTime($datetime1->format('Y-m-d'));
$datetime2modified = new DateTime($datetime2->format('Y-m-d'));
$difference = $datetime1modified->diff($datetime2modified)->d; //3
you surely could use a function like this:
$time1 = strtotime("2008-12-13 10:42:00");
$time2 = strtotime("2010-10-20 08:10:00");
$diff = $time2-$time1;
// the difference in int. then you can divide by 60,60,24 and
// so on to get the h:m:s out of it
or if you more into the build in php functions then something like this might suit your needs:
$date_a = new DateTime('2010-10-20 08:10:00');
$date_b = new DateTime('2008-12-13 10:42:00');
$interval = date_diff($date_a,$date_b);
echo $interval->format('%h:%i:%s');
best regards.
What you can do is remove the Time from each of the dates and then calculate.
example:
$datetime1 ='2009-10-11 23:30';
$datetime2 = '2009-10-12 02:30';
$date1_explode = explode($datetime1,' ');
$date1_explode = explode($datetime1,' ');
$date = $date1_explode[1];
$date = $date2_explode[1];
$date1 = new DateTime($datetime1);
$date2 = new DateTime($datetime1);
$interval = $date1->diff($date2);
echo "<pre>";
print_r($interval);
echo "</pre>";
If you don't care about the hours and want to know only if the date changed you can try to diff the dates after you set them to the same hour:
$datetime1 = new DateTime('2009-10-11 23:30');
$datetime2 = new DateTime('2009-10-12 02:30');
// Work on duplicates to not change the original objects if they are needed later
$date1 = clone $datetime1;
$date2 = clone $datetime2;
// Set the same hour on both $date1 and $date2
$date1->setTime(0, 0, 0);
$date2->setTime(0, 0, 0);
// Now you can simply compare $date1 to $date2 to see if they are equal
if ($date1 == $date2) {
echo('$datetime1 and $datetime2 are on the same date.');
} else {
echo('$datetime1 and $datetime2 are on different dates.');
}
// Or you can compute the difference
$diff = $date2->diff($date1);
// and format it as you like
echo('There are '.$diff->format('%d').' days between '.$date1.' and '.$date2);
Related
consider that i have 2 dates like below in my view :
{{$property->start_date }} //which is for example 3/20/219
and another date
{{$property->end_date }} //which is for example 3/28/219
now i want to some how print these 8 days of difference as 8 col-lg-1 some how like below code
#while($property->start_date <= $property->end_date)
//here i want to print dates in col-lg-1 i dont know how to access the day and if the while loop is working right or no
how can i achieve that in blade considering this that i am doing this in my view and is it reasonable at all to do it in view or not .
You can use the CarbonPeriod from Carbon
something like this
$ranges = CarbonPeriod::create('2019-03-01', '2019-03-31');
To print each date you can use the loop
foreach ($ranges as $date) {
echo $date->format('Y-m-d');
}
Or you can convert it to array as well
$dates = $ranges->toArray();
Return all dates between two dates in php:
Using DatePeriod and DateTime:
$begin = new DateTime($property->start_date); // your start date 2019-03-20
$begin = $begin->modify( '+1 day' );
$end = new DateTime($property->end_date); // your end date 2019-03-28
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach ($daterange as $date) {
echo '<pre>'.$date->format('Y-m-d').'<pre>';
}
Output:
2019-03-21
2019-03-22
2019-03-23
2019-03-24
2019-03-25
2019-03-26
2019-03-27
Using strtotime:
// Declare two dates
$Date1 = $property->start_date; // 2019-03-20
$Date2 = $property->end_date; // 2019-03-28
// Declare an empty array
$array = array();
// Use strtotime function
$start = strtotime($Date1. '+1 day');
$end = strtotime($Date2. '-1 day');
// Use for loop to store dates into array
// 86400 sec = 24 hrs = 60*60*24 = 1 day
for ($currentDate = $start; $currentDate <= $end; $currentDate += (86400)) {
$Store = date('Y-m-d', $currentDate);
$array[] = $Store;
}
// Display the dates in array format
echo '<pre>';
print_r($array);
echo '<pre>';
Output:
Array
(
[0] => 2019-03-21
[1] => 2019-03-22
[2] => 2019-03-23
[3] => 2019-03-24
[4] => 2019-03-25
[5] => 2019-03-26
[6] => 2019-03-27
)
I hope it would helpful.
If you want to get date diff , you can use Carbon and diffInDays .
$date1 = Carbon::parse($property->start_date);
$date2 = Carbon::parse($property->end_date );
$diff = $date1->diffInDays($date2);
dd($diff);
You can try this on template directly (only if there no way or if it's difficult to pass it from controller to view)
#php
$date1 = \Carbon\Carbon::parse('2019-01-31 10:15:23');
$date2 = \Carbon\Carbon::parse('2019-02-15 10:15:23');
$diff = $date1->diffInDays($date2);
#endphp
<div>{{$diff}}</div>
but if you do it in controller and send it to template it would be better
I would like to calculate days based on two dates but it's given incorrect count of days.
I have 2 variables
$date=$date[1]; Is coming from Database
$now =date('d/m/Y'); Current date
$date variable value is(comes from db) 05/03/2019
I used following script for count days based on two dates but its return 120 days.
Method 1
$date=$date[1]; `Is coming from Database`
$now =date('d/m/Y');
$date1 = new DateTime($now);
$date2 = new DateTime($date);
$diff = $date2->diff($date1)->format("%a");
Method 2
$datetime1 = new DateTime($now);
$datetime2 = new DateTime($date);
$difference = $datetime1->diff($datetime2);
echo 'Difference: '.$difference->y.' years, '
.$difference->m.' months, '
.$difference->d.' days';
print_r($difference);
But it's returns wrong days in following output
Difference: 0 years, 4 months, 120 daysDateInterval Object
(
[y] = 0
[m] = 4
[d] = 0
[h] = 0
[i] = 0
[s] = 0
[invert] = 0
[days] = 120
)
Why this given wrong output of days ?
If you use 'd/m/Y' format you should use createFromFormat function to convert string date to date object. For example:
$date1 = new \DateTime();
$date2 = \DateTime::createFromFormat('d/m/Y', '05/03/2019');
$diff = $date2->diff($date1)->format("%a");
I have an array which contains time values in GMT. :
Array
(
[0] => Array
(
[h] => 5
[m] => 0
)
)
Here Array[0][0] is the array for start time and Array[0][1] is the array for end time.
Now what I am creating time using date time as:
$timezone = new DateTimeZone("Asia/Kolkata"); //Converting GMT to IST.
$startTime = new DateTime();
$startTime->setTime($Array[1][0]["hour"], $Array[1][0]["minute"]);
$startTime->setTimezone($timezone);
$startTime->format('h:i a'); //output 10:30 PM // Should be 10:30 AM
$endTime = new DateTime();
$endTime->setTime($Array[1][1]["hour"], $Array[1][1]["minute"]);
$endTime->setTimezone($timezone);
$endTime->format('h:i a'); //output 10:30 PM //ok
So My $startTime and $endTime both has the same value of `10:30` PM but I want the startTime to have value of `10:00 AM`because its period was `AM` in the array.
When creating new Datetime object You have to specify timezone, because default value is taken from PHP configuration and this may not be set to GMT. So initialization of $startTime and $endTime should be:
$startTime = new DateTime('', new DateTimeZone('GMT'));
$endTime = new DateTime('', new DateTimeZone('GMT'));
Then when You are using setTime() You have to add 12 hours when PM period is taken. It should look like that:
$startTime->setTime($Array[1][0]["hour"] + ($Array[1][0]["period"] === 'PM' ? 12 : 0), $Array[1][0]["minute"]);
$endTime->setTime($Array[1][1]["hour"] + ($Array[1][1]["period"] === 'PM' ? 12 : 0), $Array[1][0]["minute"]);
Rest of the code looks fine, besides in You example $Array[1] is undefined. $Array[0] is set.
You could also use DateTime::createFromFormat():
$d = DateTime::createFromFormat('g:m A', '5:30 PM', new DateTimeZone('GMT'));
$d->setTimeZone(new DateTimeZone('Asia/Kolkata'));
var_dump($d->format('Y-m-d H:i:s'));
Gives:
string(19) "2017-03-16 22:30:00"
You can create the string '5:30 PM' by combining the elements of your array. Please note that you must add a leading 0 to the minutes if they are less than 10, e.g: 9 minutes -> 09
How can i get 2nd monday after the input date?
i have solution but that not feasible
$date = new DateTime();
$date->modify('next monday');
$next_monday = $date->format('Y-m-d');
$date = new DateTime($next_monday);
$date->modify('next monday');
$next_monday = $date->format('Y-m-d');
Please suggest me some method to do so.
Your DateTime object's modify method takes the same type of arguments that strtotime does. You're already using 'next monday', you just need to use 'second monday' instead.
$date->modify('second monday');
echo $date->format('Y-m-d');
Also, in case you didn't know this, some of the DateTime methods can be chained:
echo $date->modify('second monday')->format('Y-m-d');
You can do it with strtotime() but if you think it is too costly, you can use date and DateInterval as well.
$date = new DateTime('2017-02-15 13:03:00');
// move back to past Monday
$num = (date("w", $date->getTimestamp())) - 1;
$offset = new DateInterval("P{$num}D");
$offset->invert = 1;
// move forward two weeks
$interval = new DateInterval('P2W');
$next_second_monday = $date->add($offset)->add($interval);
And $next_second_monday will be:
DateTime Object
(
[date] => 2017-02-27 13:03:00.000000
[timezone_type] => 3
[timezone] => UTC
)
There is probably another way to do so but using MomentPHP You could get the start of today's week, adding 1 day ( to get to monday ) and then adding two week, you would get to the second next monday.Something like that :
<?php
$m = \Moment\moment();
$sunday = $m->startOf('week');
$monday = $sunday->addDays(1);
$2nextMonday = $monday->addWeeks(2);
I can't seem to get this to work. I have tried from the samples online but there wasn't one the is exactly what I needed. Basically I want to be able to display the number of days that passed from the given date. My sample below is a combined HTML and PHP, I had to do it this way for some reasons.
<?php
$OldDate = strtotime($row['DateSigned']);
$NewDate = date('M j, Y', $OldDate);
?>
<b>Date Signed:</b> <?php echo $NewDate; ?>
<b>Days Since Signed:</b> <?php echo date_diff(strtotime($NewDate),Date("y/m/d")); ?>
This seem to fail.Date("y/m/d") is the date today. Can you tell me what went wrong?
This will work:
<?php
$OldDate = strtotime("2015-10-21");
$NewDate = date('M j, Y', $OldDate);
$diff = date_diff(date_create($NewDate),date_create(date("M j, Y")));
?>
<b>Date Signed:</b> <?php echo $NewDate; ?>
<b>Days Since Signed:</b> <?php echo $diff->format('%R%a days'); ?>
using date_diff, it expects a DateTime object rather than an integer. Here is an example to get you where you may want to be
<?php
$OldDate = new DateTime('2009-10-11');
$now = new DateTime(Date('Y-m-d'));
print_r($OldDate->diff($now));
?>
This outputs (as of the day of this post) ::
[y] => 6
[m] => 0
[d] => 14
[h] => 0
[i] => 0
[s] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 2205
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
See DateTime::diff
Below is code that will get you the date difference with current date, i hope it helps.
$date = $row['DateSigned'];
$diff = date_diff(date_create($date), date_create(date('Y-m-d')));
echo $diff->format("%a");
The result you will get is number of days.
Thanks everyone, I found a simpler solution (Simpler for beginner like me to understand) :)
$now = time(); // or your date as well
$your_date = strtotime($NewDate);
$datediff = ceil(($now - $your_date)/86400);
$datediff is now showing the number of days.
It's too late to reply and there are other good answer but I would like to share what worked for me.
date_default_timezone_set("Asia/Karachi");
$old_date = new DateTime('2018-12-01 04:10:58');
$now = new DateTime(Date('Y-m-d'));
$interval = $old_date->diff($now);
echo $interval->d.' days<br>';
// you can also get years, month, hours, minutes, and seconds
echo $interval->y.' years<br>';
echo $interval->m.' months<br>';
echo $interval->h.' hours<br>';
echo $interval->i.' minutes<br>';
echo $interval->s.' seconds<br>';
Try to use timestamps.
$from = mktime(0,0,0,6,1,2015); // example old date
$to = time(); // now
echo round(($to - $from)/86400); // gives you elapsed days
86400 is the # of seconds in a day.