Php's new DateTime() is not working on my new server - php

I am trying to calculate the time interval between two Dates. So here is my code
$start_date = new DateTime("$date1");
$end_date = new DateTime("$date2");
$interval = $start_date->diff($end_date);
$days = $interval->d;
$months = $interval->m;
$years = $interval->y;
$hours = $interval->h;
$mins = $interval->i;
$secs = $interval->s;
when i try to echo the result it returns an empty result.
This same code worked on my development server and localhost, As soon as i changed to another server it stoped responding.
I checked php.ini for timezone setting, it was good.
I will be thank full for your help

Check your php.ini files inside /etc/php5/apache2/ and /etc/php5/cli/ folders. Both files must have declared the default time zone eg. date.timezone = "America/New_York"
Other way you can have it to work is declaring it inside your code before creating the DateTime object
date_default_timezone_set('America/New_York');
$start_date = new DateTime("$date1");
$end_date = new DateTime("$date2");
$interval = $start_date->diff($end_date);
$days = $interval->d;
$months = $interval->m;
$years = $interval->y;
$hours = $interval->h;
$mins = $interval->i;
$secs = $interval->s;

NOTE: I suggest that you store everything in timestamp in your database rather than in date. And in your display logic, convert it to date, or find how old it is, etc. Read this on Datetime vs timestamp Should I use field 'datetime' or 'timestamp'?
Below,find two functions to find time difference between two timestamps as well as get the age of an old timestamp compared to now.
<?php
echo whatAge(#SOME TIMESTAMP HERE#)
echo getDiff(#TIMESTAMP1, TIMESTAMP2#)
?>
This gives you day hour minute second. Modify the secondsToTime function below for something else.
Use the functions below...
function whatAge($old_time){
$current_time = getdate(time())[0];
$time_diff = $current_time-$old_time;
return secondsToTime($time_diff,'string');
}
function getDiff($time1, $time2){
$time_diff = $time1-$time2;
return secondsToTime($time_diff,'string');
}
function secondsToTime($inputSeconds, $return='array') {
/** https://stackoverflow.com/questions/8273804/convert-seconds-into-days-hours-minutes-and-seconds */
$secondsInAMinute = 60;
$secondsInAnHour = 60 * $secondsInAMinute;
$secondsInADay = 24 * $secondsInAnHour;
// extract days
$days = floor($inputSeconds / $secondsInADay);
// extract hours
$hourSeconds = $inputSeconds % $secondsInADay;
$hours = floor($hourSeconds / $secondsInAnHour);
// extract minutes
$minuteSeconds = $hourSeconds % $secondsInAnHour;
$minutes = floor($minuteSeconds / $secondsInAMinute);
// extract the remaining seconds
$remainingSeconds = $minuteSeconds % $secondsInAMinute;
$seconds = ceil($remainingSeconds);
// return the final array
$obj = array(
'd' => (int) $days,
'h' => (int) $hours,
'm' => (int) $minutes,
's' => (int) $seconds,
);
$str = function($d,$h,$m,$s){
if($d>0){
return "$d d, $h h $m m";
}else{
return "$h h $m m";
}
};
switch ($return){
case 'array' : return $obj; break;
case 'string' : return $str($obj['d'],$obj['h'],$obj['m'],$obj['s']); break;
}
}

Simple Way
Try this:
$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
read more [php DateTime::diff manual][1]

Related

Hour, Minute difference in php

I am looking a solution in Php.
I have a total time for a task in hh:mm:ss format. (Date is not important).
and I am entering each working time also in hh:mm:ss format. Now I have to find out the remain hours in hh:mm:ss format.
Example
16:00:00 is the assigned hours to do a task.
In different dates one employee worked 13:15:00 hours
Now I need the remaining hours as 2:45:00 in format.
If date is attached then we can do like
datetime1 = new DateTime('2014-02-11 04:04:26 AM');
$datetime2 = new DateTime('2014-02-11 05:36:56 AM');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%h')." Hours ".$interval->format('%i')." Minutes";
In my case there is no date. is there any functionality in PHP to find this type of hh:mm:ss difference?
Convert your HH:MM:SS format to a duration in seconds, subtract them, format them back to HH:MM:SS:
function str_to_seconds($duration) {
list($h, $m, $s) = explode(':', $duration);
return $s + ($m * 60) + ($h * 3600);
}
function seconds_to_str($seconds) {
return sprintf('%02d:%02d:%02d', $seconds / 3600, $seconds / 60 % 60, $seconds % 60);
}
echo seconds_to_str(str_to_seconds('16:00:00') - str_to_seconds('13:15:00'));
You must convert it to timestamp, then calculate the difference and format that difference to appear like a normal date.
Something like this:
function dateDifference($date_1 , $date_2 , $differenceFormat = '%a' )
{
$datetime1 = date_create($date_1);
$datetime2 = date_create($date_2);
$interval = date_diff($datetime1, $datetime2);
return $interval->format($differenceFormat);
}
Super short version
$secondsDiff = abs(strtotime("2014-02-11 04:04:26 AM") - strtotime("2014-02-11 05:36:56 AM"));
echo sprintf("%02d", floor($secondsDiff / 3600)) . ":" . sprintf("%02d", floor($secondsDiff / 60 %60)) . ":" . sprintf("%02d", ($secondsDiff % 60));

Calculate time difference with formatted time

I have two times: a starting time and the duration. I want to subtract the duration from the starting time. The time I read from an mysql db and is already formatted. My code:
$start= $row["start"]; //output is for e.g. 08:00:00
$dur = $row["duration"]; //output is for e.g. 01:00:00
$sub = $start - $dur;
// I want the output to be 07:00:00
// the result now is 7 and I got an error (non well formed numeric value)
Can someone help me?
Alternatively you can achieved like this
$date = "1970-01-01";
$start = $date." ".$row["start"];
$dur = $date ." ".$row["duration"];
$date1=date_create($start);
$date2=date_create($dur);
$diff=date_diff($date1,$date2);
echo $diff->format("%H:%I:%S");
$start= "08:00:00";
$dur = "01:00:00";
$diff = differenceInHours($start, $dur);
echo convertTime($diff);
function differenceInHours($startdate,$enddate){
$starttimestamp = strtotime($startdate);
$endtimestamp = strtotime($enddate);
$difference = abs($endtimestamp - $starttimestamp)/3600;
return $difference;
}
function convertTime($dec)
{
// start by converting to seconds
$seconds = ($dec * 3600);
// we're given hours, so let's get those the easy way
$hours = floor($dec);
// since we've "calculated" hours, let's remove them from the seconds variable
$seconds -= $hours * 3600;
// calculate minutes left
$minutes = floor($seconds / 60);
// remove those from seconds as well
$seconds -= $minutes * 60;
// return the time formatted HH:MM:SS
return lz($hours).":".lz($minutes).":".lz($seconds);
}
// lz = leading zero
function lz($num)
{
return (strlen($num) < 2) ? "0{$num}" : $num;
}
You should always save date in your database in the appropriate format. And not as a "already formated" value. Except in very specific case.
Anyway, to solve your problem you can do soemthing like this
$start = new DateTime('08:00:00');
$duration = new DateTime('01:00:00');
$interval = date_diff($start, $duration);
echo $interval->format('%H:%I:%S'); //ouput will be 07:00:00

Add fractional hours to a DateTime in php

I have a system which I need to add a certain amount of fractional hours.
I've been searching and this is what I got, by far it's the most accurate method, but still doesn't give me the answer I need
function calculateHours($hours){
$now = new DateTime("2017-10-25 10:23:00");
$time = array();
$time = explode(".", $hours);
$time [1] += $time [0]*60;
$now->modify("+".$time[1]." hours");
return $now;
}
$diff = 119.23;
$answer = calculateHours($diff);
echo $answer ->format('Y-m-d H:i:s');
The answer that I want to reach is "2017-11-09 11:00:00" and I receive "2017-10-25 12:22:23" instead
Adding the hours is not correct. When you multiply hours times 60 it will make minutes.
This code should work.
function calculateHours($hours){
$now = new DateTime("2017-10-25 10:23:00");
$time = explode(".", $hours);
$time[1] += $time[0]*60;
$now->modify("+".$time[1]." minutes");
return $now;
}
$diff = 119.23;
$answer = calculateHours($diff);
echo $answer->format('Y-m-d H:i:s');
Result is 2017-10-30 09:46:00
You should use DateInterval php class to create an inverval with x seconds from your $hours variable.
Then you just have to use the datetime add interval method to modify your date
Please take a look a this example
function calculateHours($hours){
$now = new DateTime("2017-10-25 10:23:00");
var_dump($now);
$timeParts = explode(".", $hours);
// Where 23 is a percentage of on hour
$minutes = $timeParts[0] * 60 + round($time[1] * 60 / 100);
// Where 23 is the number of minutes
$minutes = $timeParts[0] * 60 + $time[1];
$interval = new DateInterval(sprintf('PT%dM', $minutes));
$now->add($interval);
echo $now->format('Y-m-d H:i:s');
return $now;
}
Use date_add
date_add($now, date_interval_create_from_date_string($tempo[1]' hours'));
or as object:
$now->add( DateInterval::createFromDateString($tempo[1].' hours'));

PHP: Days, hours and minutes left to a certain date?

I'm trying to get remaining Days, hours and minutes to a certain date using php.
However i get a very strange output from my code which looks like this:
-16828 days and -11 hours and -21 minutes and -24 seconds
The future dates are stored in the mysql database in this format:
29/01/2016 7pm
So I went ahead and done this:
$Draw_time = "29/01/2016 7pm";
$date = $Draw_time;
$timestamp = strtotime($date);
$new_date = date('Y-m-d a',$timestamp );
$seconds = strtotime($new_date) - time();
$days = floor($seconds / 86400);
$seconds %= 86400;
$hours = floor($seconds / 3600);
$seconds %= 3600;
$minutes = floor($seconds / 60);
$seconds %= 60;
echo "$days days and $hours hours and $minutes minutes and $seconds seconds";
But when i run this code, I get the above strange output!
I understand that this could be because of a number reasons but the only thing i could think of is the fact that I am using a in my format?
Could someone please advise on this issue?
Simply use DateTime class like as
$Draw_time = "29/01/2016 7pm";
$date = DateTime::createFromFormat("d/m/Y ha",$Draw_time);
$date2 = new DateTime();
echo $diff = $date2->diff($date)->format("%a days and %H hours and %i minutes and %s seconds");
Try this
<?php
$Draw_time = str_replace('/', '-', "29/01/2016 7pm");
$now = new DateTime();
$futureDate = new DateTime($Draw_time);
$interval = $futureDate->diff($now);
echo $interval->format("%a days %h hours %i minutes %s seconds");
?>
Try this.
$draw_time = "2016/01/29 7pm";
$date_time = explode(" ", $draw_time);// make separate date and time in array
$date = strtotime($date_time[0]); // convert your date(2016/01/29) into php time
$time = strtotime($date_time[1]); // convert your time(7pm) into php time
$date = $date + $time; // make total time to count
$new_Date = $date - (time()); // convert into difference from current time
$day = $new_Date % 86400;
$hrs = $new_Date % 3600;
$min = $new_Date % 60;
echo "Day= ".(date("d",$day));
echo " Hours= ".(date("h",$hrs));
echo " Minutes= ".(date("i",$min));

How do I find the hour difference between two dates in PHP?

I have two dates, formated like "Y-m-d H:i:s". I need to compare these two dates and figure out the hour difference.
You can convert them to timestamps and go from there:
$hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);
Dividing by 3600 because there are 3600 seconds in one hour and using round() to avoid having a lot of decimal places.
You can use DateTime class also -
$d1= new DateTime("06-08-2015 01:33:26pm"); // first date
$d2= new DateTime("06-07-2015 10:33:26am"); // second date
$interval= $d1->diff($d2); // get difference between two dates
echo ($interval->days * 24) + $interval->h; // convert days to hours and add hours from difference
As an addition to accepted answer I would like to remind that \DateTime::diff is available!
$f = 'Y-m-d H:i:s';
$d1 = \DateTime::createFromFormat($date1, $f);
$d2 = \DateTime::createFromFormat($date2, $f);
/**
* #var \DateInterval $diff
*/
$diff = $d2->diff($d1);
$hours = $diff->h + ($diff->days * 24); // + ($diff->m > 30 ? 1 : 0) to be more precise
\DateInterval documentation.
$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 / 60;
You can try this :
$time1 = new DateTime('06:56:58');
$time2 = new DateTime('15:35:00');
$time_diff = $time1->diff($time2);
echo $time_diff->h.' hours';
echo $time_diff->i.' minutes';
echo $time_diff->s.' seconds';
Output:
8 hours 38 minutes 2 seconds
The problem is that using these values the result is 167 and it should be 168:
$date1 = "2014-03-07 05:49:23";
$date2 = "2014-03-14 05:49:23";
$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 / 60;
$date1 = date_create('2016-12-12 09:00:00');
$date2 = date_create('2016-12-12 11:00:00');
$diff = date_diff($date1,$date2);
$hour = $diff->h;
This is because of day time saving.
Daylight Saving Time (United States) 2014 began at 2:00 AM on
Sunday, March 9.
You lose one hour during the period from $date1 = "2014-03-07 05:49:23" to
$date2 = "2014-03-14 05:49:23";
You can try this:
$dayinpass = "2016-09-23 20:09:12";
$today = time();
$dayinpass= strtotime($dayinpass);
echo round(abs($today-$dayinpass)/60/60);
You can use strtotime() to parse your strings and do the difference between the two of them.
Resources :
php.net - strtotime()

Categories