Calculate time difference in php - php

I am trying to calculate time different between 3 different dates
1. Start date
2. End date
3 current date
I have been researching on how to calculation but couldn't find any exact example.
Any assistance in resolving this would be appreciated.
function getweekSartEndDate($date){
$cur_date = strtotime($date); // Change to whatever date you need
// Get the day of the week: Sunday = 0 to Saturday = 6
$dotw = date('w', $cur_date);
if($dotw>1){
$pre_monday = $cur_date-(($dotw-1)*24*60*60);
$next_sunday = $cur_date+((7-$dotw)*24*60*60);
}
else if($dotw==1){
$pre_monday = $cur_date;
$next_sunday = $cur_date+((7-$dotw)*24*60*60);
}
else if($dotw==0){
$pre_monday =$cur_date - (6*24*60*60);;
$next_sunday = $cur_date;
}
$date_array = array();
$date_array['weekStart'] = $pre_monday;
$date_array['weekEnd'] = $next_sunday;
return $date_array;
}
The above is the example code i got so far, and i was able to get the start and end dates of a week as seen below:
$weekStart = date('Y-m-d H:i:s', $weekInfo['weekStart']);
$weekEnd = date('Y-m-d H:i:s', $weekInfo['weekEnd']);
My challenges is how to get the time difference in 'Y-m-d H:i:s' date format from the current time.

You can use
$currentDate = date('Y-m-d H:i:s');
$currentDate = new DateTime($currentDate);
$leaveDate = new DateTime($leaveFrom);
$difference = $currentDate->diff($leaveDate);
You will get result as follow
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 0 [s] => 0 [f] => 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 )

You need basic knowledge on how to do number comparisons in PHP.
Convert your date strings to a UNIX-timestamp with strtotime
$d = strtotime("19/10/2016 14:48:21");
// 1519646232
When the dates are in UNIX-timestamp format, it's easy to compare them with any regular comparison operators as int numbers.
EDIT
Difference in seconds:
$diffBetweenStartAndNow = strtotime( $date_array['weekStart'] ) - time();
$diffBetweenEndAndNow = strtotime( $date_array['weekEnd'] ) - time();

Related

PHP - Hours difference is not accurate using DateTime object

I am trying to get difference in hours between two dates using PHP DateTime object but the result is not accurate. One date is the current date time and second is the event date which comes from database. I don't understand on what logic the hours difference is calculated.
Here's my code:
<?php
$date1 = new DateTime();
$date2 = new DateTime("2018-09-04 20:37:06");
$interval = $date2->diff($date1);
echo "<pre>";
print_r($interval);
echo "</pre>";
echo $interval->format('%a Day and %h hours');
?>
Output:
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 3
[i] => 14
[s] => 13
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 1
[days] => 0
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
0 Day and 3 hours
The script is executed at 08:53 PM (India) i.e. 20:53:00 but the difference is 3 hours. Don't know why?
For Indian time this should help :-
<?php
$timezone = new DateTimeZone('Asia/Kolkata');
$date1 = new DateTime('now', $timezone);
$date2 = new DateTime("2018-09-04 20:37:06", $timezone);
$interval = $date2->diff($date1);
echo "<pre>";
print_r($interval);
echo "</pre>";
echo $interval->format('%a Day and %h hours');
?>
Just use the DateTimeZone('Zone') and it should set the new date to the zone where you are.

Show dates between two dates

I have a leave system where user select dates from and to dates let say 2018-02-26 - 2018-03-03 that is 6 days in total. On our portal it shows all users that is on leave. supposing that this user applied for 6 days leave, How am I going to display this user for 6 days on our portal?below is my code it works well but is show only for the current date.
$currentDate = date('Y-m-d');
$lf = Leave::where('leave_from', $currentDate)
->where('status', 'approved')
->get();
I am using eloquent. thanks
// Specify the start date. This date can be any English textual format
$date_from = "2018-02-03";
$date_from = strtotime($date_from); // Convert date to a UNIX timestamp
// Specify the end date. This date can be any English textual format
$date_to = "2018-02-10";
$date_to = strtotime($date_to); // Convert date to a UNIX timestamp
// Loop from the start date to end date and output all dates inbetween
for ($i=$date_from; $i<=$date_to; $i+=86400) {
echo date("Y-m-d", $i).'<br />';
}
You can use datetime function in PHP.
$first_date = new DateTime($currentDate);
$last_date = new DateTime($if);
$difference = $first_date->diff($last_date);
echo $difference->d.' days;
if you want month and year use $difference->m and $difference->y.And if you want accurate days even dates are negative use below one.
$result = $first_date->diff($last_date)->format("%r%a");
source:/ datetime
You can use date_diff() function:
$interval = date_diff($currentDate, $lf);
echo $interval->format('%d');
more on: http://php.net/manual/en/function.date-diff.php; https://www.w3schools.com/php/func_date_date_diff.asp
You can use DATEDIFF to get difference directly from query.
Select abs(DATEDIFF(`date_to`,`date_from`)) as diff from leaves;
In laravel you can write it as
$lf = Leave::where('status', 'approved')
->select(DB::raw("abs(DATEDIFF(`date_to`,`date_from`)) as diff"),"*")
->get();
Be sure to use where('leave_from', $currentDate), I think it's not necessary.
You can use DateTime function of PHP
in your case
$currentDate = date('Y-m-d');
$currentDate = new DateTime($currentDate);
$leaveDate = new DateTime($leaveFrom);
$difference = $currentDate->diff($leaveDate);
You will get result like
DateInterval Object ( [y] => 0 [m] => 0 [d] => 5 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 5 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
$many_days=0;
$date_from = "2018-02-26";
$date_to = "2018-03-03";
for ($i=strtotime($date_from); $i<=strtotime($date_to);
$i+=86400) {
$many_days++;
}
echo "leaves $many_days";

PHP Comparing Current Date to a Given Date

I am having a hard time getting a simple date check to work properly. I searched all the questions, and so far none of the solutions have helped me.
I want to do a loop from a certain date, until today.
What is currently happening with the below code is that its not stopping and just keeps going. When I log i, I can see the date is increasing by a day like it should. I also tried flipping the operator to <, but that caused the loop to be skipped entirely.
Any ideas?
$startOfPlayoffs = new DateTime( "2016-04-29" );
$today = date("Y-m-d");
for($i = $startOfPlayoffs; $i >= $today; $i->modify('+1 day'))
{
//... some stuff
}
Interestingly, when I hard-code the date, it works fine. I.E:
$endOfPlayoffs = new DateTime( "2016-05-02" );
That isn't ideal, so was hoping to get it to work properly.
You are comparing a PHP Date object ($startOfPlayoffs) with a string ($today). Try converting $today into a Date object:
$startOfPlayoffs = new DateTime("2016-04-29");
$today = new DateTime();
$cpt = 0;
for($i = $startOfPlayoffs; $i <= $today; $i->modify('+1 day')){
echo time($i) . "<br>";
if ($cpt++ >= 100) exit;// as a safeguard
}
use unix time stamps, they are concrete numbers that are much easier to deal with.
int time(void) //current time stamp
You can also use strtotime() to convert date strings into time stamps. See this question for conversion from numbered date formats to unix timestamps.
Use the ->diff() method of the DateTime class like this is quite clean
The ->diff() method produces an DateInterval Object that looks like this
DateInterval Object
(
[y] => 0
[m] => 3
[d] => 4
[h] => 17
[i] => 23
[s] => 4
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 95
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
So the code can be as simple as this
<?php
$startOfPlayoffs = new DateTime( "2016-01-29" );
$today= new DateTime();
$diff = $startOfPlayoffs ->diff($today);
for ( $i = 0; $i<$diff->days; $i++ ) {
// do stuff
}
use: date_format($startOfPlayoffs,"Y-m-d") to obtain a "variable" you can compare against...
$startOfPlayoffs = new DateTime( "2016-04-29" );
$today = date("Y-m-d");
for($i = date_format($startOfPlayoffs,"Y-m-d"); $i >= $today; $i->modify('+1 day'))
{
//... some stuff
}

How to calculate time difference between SQL time and PHP time

I have set times in SQL in this format: 2016-01-03 12:13:26.
I would like to calculate the number of hours and minutes (if hours<1) going from NOW() to that particular SQL time.
I've been looking at all the different threads here but I can't seem to grasp how to convert PHP different time formats to SQL's.
This is the code I've been using, but this will only give me back hours up to 12, and minutes also. Don't know how to use it with days.
$now = date("d/m/Y h:i:s");
$commentime = strtotime($SQLTIME);
$timetocomment = $now - $commentime;
For instance, this code will yield "12 hours ago" for data I posted 24 hours ago to SQL.
How can I do it? Thank you.
This is my suggestion to use date() in this format date("Y-m-d h:i:s"). Than you will get the complete difference in an array.
function dateDifference($date_1 ,$date_2)
{
$datetime1 = date_create($date_1);
$datetime2 = date_create($date_2);
$interval = date_diff($datetime1, $datetime2);
return $interval;
}
$now = date("Y-m-d h:i:s");
$sqlTime = "2016-01-03 12:13:26";
$DateDiffArr = dateDifference($now,$sqlTime);
echo "<pre>";
print_r($DateDiffArr);
Result Is:
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 22
[i] => 45
[s] => 55
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 1
[days] => 0
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
In resultant array, you can get the all difference as you need like in years, months, days, minutes, seconds etc.

PHP Finding how many hours of a timespan is within another timespan

I am trying to find a way to determine whether a timespan is partially or fully within another timespan. For example:
I have time entries of:
Monday 18:30:00 to Tuesday 05:00:00,
Monday 23:00:00 to Tuesday 05:00:00,
Monday 20:00:00 to Tuesday 08:00:00,
Monday 00:00:00 to Tuesday 08:00:00,
and need to find, for each one, how much of the time is within a timespan of 22:00:00 to 06:00:00. The output would need to be:
07:00:00,
06:00:00,
08:00:00,
06:00:00.
What you're looking for is DateTime::diff which returns an instance of an DateInterval
Here a little example:
$d1 = new DateTime("Monday 18:30:00");
$d2 = new DateTime("Tuesday 05:00:00");
$limit1 = new DateTime("Monday 22:00:00");
$limit2 = new DateTime("Tuesday 06:00:00");
$within1 = $d1->getTimestamp() < $limit1->getTimestamp() ? $limit1 : $d1;
$within2 = $d2->getTimestamp() < $limit2->getTimestamp() ? $d2 : $limit2;
$interval = $within1->diff($within2);
print_r($interval);
print_r($interval);
outputs:
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 7
[i] => 0
[s] => 0
[invert] => 0
[days] => 0
)
You can either read this attributes directly or you can use the DateInterval::format()

Categories