Difference between two datetime strings: setting timezone - php

//Difference between 2 dates
This function works well but display wrong time format. Pls how can I change the time of this function from GMT to GMT+1? Displays 15hrs 22mins instead of 16hrs 22mins.
Thanks
function get_date_diff($start, $end="NOW")
{
$sdate = strtotime($start);
$edate = strtotime($end);
$timeshift = "";
$time = $edate - $sdate;
if($time>=0 && $time<=59) {
// Seconds
$timeshift = $time.' seconds ';
} elseif($time>=60 && $time<=3599) {
// Minutes + Seconds
$pmin = ($edate - $sdate) / 60;
$premin = explode('.', $pmin);
$presec = $pmin-$premin[0];
$sec = $presec*60;
$timeshift = $premin[0].' min '.round($sec,0).' sec '."<b>ago</b>";
} elseif($time>=3600 && $time<=86399) {
// Hours + Minutes
$phour = ($edate - $sdate) / 3600;
$prehour = explode('.',$phour);
$premin = $phour-$prehour[0];
$min = explode('.',$premin*60);
$presec = '0.'.$min[1];
$sec = $presec*60;
$timeshift = $prehour[0].' hrs '.$min[0].' min '.round($sec,0).' sec '."<b>ago</b>";
} elseif($time>=86400) {
// Days + Hours + Minutes
$pday = ($edate - $sdate) / 86400;
$preday = explode('.',$pday);
$phour = $pday-$preday[0];
$prehour = explode('.',$phour*24);
$premin = ($phour*24)-$prehour[0];
$min = explode('.',$premin*60);
$presec = '0.'.$min[1];
$sec = $presec*60;
$timeshift = $preday[0].' days '.$prehour[0].' hrs '.$min[0].' min '.round($sec,0).' sec '."<b>ago</b>";
}
return $timeshift;
}

Set the timezone using the date_default_timezone_set() function. If that doesn't work, you have PHP <5.1.0 and should set the TZ environment variable. Check here for the detailed order of preference used to determine the timezone.
You could also skip all that code you wrote and use the date() function to get the resulting datetime string in pretty much any format you desire.

Related

Time conversion to hours and minutes with am and pm

Currently, I have data as below. But, it wasn't a timestamp value. It was a time itself
$start_time = '150630';
$end_time = '180630';
I want to change the format like 03:06 PM – 06:06 PM i tried
$init = 150630;
$hours = floor($init / 3600);
$minutes = floor(($init / 60) % 60);
$seconds = $init % 60;
echo "$hours:$minutes:$seconds";
But the format and value is not as expected.
Please help me how to solve this
You doesn't need time converter as your string wasn't a valid timestamp. Instead, it was time itself. You just need to extract the hour, min, and second.
Refer below
<?php
$start_time = "150630";
$hours = substr($start_time, 0, 2); // this is actual hours
$mins = substr($start_time, 2, 2); // this is actual minutes
$secs = substr($start_time, 4, 2); // this is actual seconds
if ($hours < 12) {
$actTime = "$hours:$mins:$secs AM";
} else {
$actTime = ($hours-12).":$mins:$secs PM";
}
echo $actTime; // this is the time format you want
You can use str_split function as your time format is not timestamp.
It will extract hours, minutes and seconds.
check the below code :
<?php
$start_time = '150630';
$end_time = '180630';
$startTimeA = str_split($start_time, 2);
$endTimeA = str_split($end_time, 2);
$startTime = "";
$AmOrPm = "AM";
if ($startTimeA[0] > 12) {
$startTime .= (int) ($startTimeA[0] - 12);
$AmOrPm = "PM";
}
echo $startTime .= ":" . $startTimeA[1] . " " . $AmOrPm;
$endTime = "";
$AmOrPm = "AM";
if ($endTimeA[0] > 12) {
$endTime .= (int) ($endTimeA[0] - 12);
$AmOrPm = "PM";
}
echo $endTime .= ":" . $endTimeA[1] . " " . $AmOrPm;
?>
Use Php Date Function And Strtotime
strtotime — Parse about any English textual datetime description into a Unix timestamp.
And Convert It like
echo $start_time = date('h:i:a' , strtotime(150630));
//o/p 03:06:pm

PHP - Find the difference between two times

I'm trying to calculate the time difference (in hours) between two times inputted via a timepicker. I have working JavaScript code, but would rather use server side code to make this calculation as it's quite important. If you want me to post the working JS code let me know in comments.
Calculating the difference between the times is easy enough, but I require the output in a particular format. For example inputs of '07:30' and '14:00' would return 6.5 rather than 6.3. The reason for this is to make it easier for me to use this time difference in calculations.
PHP Code i've tried:
Attempt #1:
<?php
$start_time = new DateTime('07:30');
$end_time = new DateTime('14:00');
$time_diff = date_diff($start_time,$end_time);
echo $time_diff->format('%h.%i');
?>
Returns 6.3 as expected.
Attempt #2:
<?php
$start_time = "07:30";
$end_time = "14:00";
$start_time = str_replace(":", "", $start_time);
$end_time = str_replace(":", "", $end_time);
$res = $end_time - $start_time;
$result = $res / 100;
echo $result;
?>
Returns 6.7.
Tool used to test output: http://codepad.viper-7.com/
Just extract the minutes:
<?php
$start_time = new DateTime('07:30');
$end_time = new DateTime('14:00');
$time_diff = date_diff($start_time,$end_time);
$hours = (int)$time_diff->format('%h');
$hour_part = ((int)$time_diff->format('%i')) / 60;
echo $hours + $hour_part;
?>
Make sure to change the type to (int) before any calculations.
If you divide the minutes by 60 you will get what part of a hour they represent.
<?php
$start_time = new DateTime('07:30');
$end_time = new DateTime('14:00');
$time_diff = date_diff($start_time,$end_time);
echo $time_diff->format('%h') + $time_diff->format('%i')/60;
?>
Returns 6.5 as expected.
You can try this:
<?php
$start_time = strtotime("07:30");
$end_time = strtotime("14:00");
$diff = $end_time - $start_time;
echo $diff;
1 hour = 60 min.
Demo.
$start_time = "07:30";
$end_time = "14:00";
list($h1, $m1) = explode(':', $start_time);
list($h2, $m2) = explode(':', $end_time);
// 1 hr = 60 min
$res = ($h2*60 - $m2) - ($h1*60 + $m1);
$result = floor($res/60) .'.'. $res % 60;
echo $result;
Try this
function time_difference($time1, $time2) {
$time1 = strtotime("1980-01-01 $time1");
$time2 = strtotime("1980-01-01 $time2");
if ($time2 < $time1) {
$time2 += 86400;
}
return date("H:i:s", strtotime("1980-01-01 00:00:00") + ($time2 - $time1));
}
echo time_difference("11:30:30", "22:40:59");
You can use this function to get the time difference between two times:
function timeBetween($start_date,$end_date)
{
$diff = $end_date-$start_date;
$seconds = 0;
$hours = 0;
$minutes = 0;
if($diff % 86400 <= 0){$days = $diff / 86400;} // 86,400 seconds in a day
if($diff % 86400 > 0)
{
$rest = ($diff % 86400);
$days = ($diff - $rest) / 86400;
if($rest % 3600 > 0)
{
$rest1 = ($rest % 3600);
$hours = ($rest - $rest1) / 3600;
if($rest1 % 60 > 0)
{
$rest2 = ($rest1 % 60);
$minutes = ($rest1 - $rest2) / 60;
$seconds = $rest2;
}
else{$minutes = $rest1 / 60;}
}
else{$hours = $rest / 3600;}
}
if($days > 0){$days = $days.' days, ';}
else{$days = false;}
if($hours > 0){$hours = $hours.' hours, ';}
else{$hours = false;}
if($minutes > 0){$minutes = $minutes.' minutes, ';}
else{$minutes = false;}
$seconds = $seconds.' seconds';
return $days.''.$hours.''.$minutes.''.$seconds;
}

Cannot redeclare date_diff() in PHP 5.3.28

I've read that this function should work in 5.3 but not 5.2 so I am unsure why I am getting fatal errors from PHP. Sadly I am not a coder by any means, was hoping I could get some guidance. Thanks!
function date_diff($start, $end="NOW")
{
$sdate = strtotime($start);
$edate = strtotime($end);
$time = $edate - $sdate;
if($time>=86400) {
// Days + Hours + Minutes
$pday = ($edate - $sdate) / 86400;
$preday = explode('.',$pday);
$phour = $pday-$preday[0];
$prehour = explode('.',$phour*24);
$premin = ($phour*24)-$prehour[0];
$min = explode('.',$premin*60);
$presec = '0.'.$min[1];
$sec = $presec*60;
$timeshift = $preday[0];
}else{
$timeshift = 0;
}
return $timeshift;
}
Cannot redeclare XXXX() simply means that you are trying to declare somethign that already exists.
The date_diff function has already been defined so check if it is already defined before defining it again. You can do this using function_exists()
if (!function_exists("date_diff"))
{
function date_diff($start, $end="NOW")
{
$sdate = strtotime($start);
$edate = strtotime($end);
$time = $edate - $sdate;
if($time>=86400) {
// Days + Hours + Minutes
$pday = ($edate - $sdate) / 86400;
$preday = explode('.',$pday);
$phour = $pday-$preday[0];
$prehour = explode('.',$phour*24);
$premin = ($phour*24)-$prehour[0];
$min = explode('.',$premin*60);
$presec = '0.'.$min[1];
$sec = $presec*60;
$timeshift = $preday[0];
}else{
$timeshift = 0;
}
return $timeshift;
}
}
Just to clarify, you only need to define the function like this is you want your code to work on versions of php newer AND older than 5.3 If you are only using 5.3+ then you do not need to declare this function at all as it already exists, you can just use date_diff() without defining it

Add up hh:mm written as a string together in php

I am trying to get a total time from few times written as a strings in php.
Times as strings:
00.25, 07.35, 01.10, 00.00, 01.00, 00.22
With that I should get 10hrs12mins but I get 11hrs03mins.
function add()
{
$midnight = strtotime('0.00');
$extra = strtotime(hours($extratime));
$taxi = strtotime(hours($taxitime));
$flt = strtotime($flttime);
$res = strtotime(hours($options->restime));
$hold = strtotime(hours($holdtime));
$totalseconds = $extra + $taxi + $flt + $res + $hold;
return date("H.i", $midnight + $totalseconds);
}
$holdtime, $taxitime, $extratime, $options->restime are all written as minutes and then converted to hours using:
function hours($min)
{
$mins = abs($min);
$neg = ($min < 0) ? '-' : '' ;
$hours = $mins / 60;
$onlyhours = floor($hours);
$onlymins = $mins - ($onlyhours*60);
$time = sprintf("%s%d.%02d",$neg,$onlyhours,$onlymins);
return $time;
}
The function hours works fine but function add doesn't as after displaying it I get 11.03 where it should be 10.12.
Thanks in advance,
Maciej.
Do not convert $holdtime, $taxitime, $extratime, $options->restime in hours.
Add these durations in minutes :
$total = $holdtime + $taxitime + $extratime + $options->restime;
Then convert $total in hours.

PHP Countdown to Date

How could set a date and get a countdown in PHP? For example if I set the date as 3 December 2PM it would tell me how many days and hours are remaining.
No need for user inputs for the date as it will be hard coded.
Thanks.
You can use the strtotime function to get the time of the date specified, then use time to get the difference.
$date = strtotime("December 3, 2009 2:00 PM");
$remaining = $date - time();
$remaining will be the number of seconds remaining. Then you can divide that number to get the number of days, hours, minutes, etc.
$days_remaining = floor($remaining / 86400);
$hours_remaining = floor(($remaining % 86400) / 3600);
echo "There are $days_remaining days and $hours_remaining hours left";
Let me play around like this:
$rem = strtotime('2012-08-01 14:00:00') - time();
$day = floor($rem / 86400);
$hr = floor(($rem % 86400) / 3600);
$min = floor(($rem % 3600) / 60);
$sec = ($rem % 60);
if($day) echo "$day Days ";
if($hr) echo "$hr Hours ";
if($min) echo "$min Minutes ";
if($sec) echo "$sec Seconds ";
echo "Remaining...";
Try this at your leisure... :-)
NOTE: There is no if() test for echo "Remaining...", just coz you wont process this in case when $rem <= 0. Isn't it?
PHP 5.3 allows this:
$dt_end = new DateTime('December 3, 2009 2:00 PM');
$remain = $dt_end->diff(new DateTime());
echo $remain->d . ' days and ' . $remain->h . ' hours';
It's not as trivial as subtracting strtotime() results, since there are daylight savings and time would be mathematically correct, but not physically. Anyway, for these purposes you should use gmdate() function, which has no daylight savings:
$date = gmdate('U', strtotime('2009-12-03 14:00'));
// Get difference between both dates without DST
$diff = $date - gmdate('U');
// Days (in last day it will be zero)
$diff_days = floor($remaining / (24 * 60 * 60));
// Hours (in the last hour will be zero)
$diff_hours = floor($remaining % (24 * 60 * 60) / 3600);
Using #Izhar Aazmi solution, you could set this up nicely for display, as such:
public function countdown($time, $h = true, $m = true, $s = true) {
$rem = $time - time();
$day = floor($rem / 86400);
$hr = floor(($rem % 86400) / 3600);
$min = floor(($rem % 3600) / 60);
$sec = ($rem % 60);
if ( $day && !$h ) {
if ( $hr > 12 ) $day++; // round up if not displaying hours
}
$ret = Array();
if ( $day && $h ) $ret[] = ($day ? $day ." day".($day==1?"":"s") : "");
if ( $day && !$h ) $ret[] = ($day ? $day . " day" . ($day == 1 ? "" : "s") : "");
if ( $hr && $h ) $ret[] = ($hr ? $hr ." hour" . ($hr==1?"":"s") : "");
if ( $min && $m && $h ) $ret[] = ($min ? $min ." minute". ($min==1?"":"s") : "");
if ( $sec && $s && $m && $h ) $ret[] = ($sec ? $sec ." second".($sec==1?"":"s") : "");
$last = end($ret);
array_pop($ret);
$string = join(", ", $ret)." and {$last}";
return $string;
}
I hope this helps! It's a nice clean way or displaying the countdown.
Did this countdown until the end of the semester:
$endOfSemester = mktime(15,30,0,5,21,2015);
$now = time();
$secondsRemaining = $endOfSemester - $now;
define('SECONDS_PER_MINUTE', 60);
define('SECONDS_PER_HOUR', 3600);
define('SECONDS_PER_DAY', 86400);
$daysRemaining = floor($secondsRemaining / SECONDS_PER_DAY); //days until end
$secondsRemaining -= ($daysRemaining * SECONDS_PER_DAY); //update variable
$hoursRemaining = floor($secondsRemaining / SECONDS_PER_HOUR); //hours until end
$secondsRemaining -= ($hoursRemaining * SECONDS_PER_HOUR); //update variable
$minutesRemaining = floor($secondsRemaining / SECONDS_PER_MINUTE); //minutes until end
$secondsRemaining -= ($minutesRemaining * SECONDS_PER_MINUTE); //update variable
echo("<h3>There are $daysRemaining days, $hoursRemaining hours, $minutesRemaining minutes, $secondsRemaining seconds until the end of the semester</h3>"); //print message
For those looking for a function capable of handling larger and smaller time span (php >5.3) :
/**
* Return a textual representation of the time left until specified date
*/
function timeleft(DateTime $date){
$now = new DateTime();
if($now > $date){
return '0 second';
}
$interval = $date->diff($now);
if($interval->y){
return $interval->format("%y year").($interval->y > 1 ? 's':'');
} else if($interval->m){
return $interval->format("%m month").($interval->m > 1 ? 's':'');
} else if($interval->d){
return $interval->format("%d day").($interval->d > 1 ? 's':'');
} else if($interval->h){
return $interval->format("%h hour").($interval->h > 1 ? 's':'');
} else if($interval->i){
return $interval->format("%i minute").($interval->i > 1 ? 's':'');
} else if($interval->s) {
return $interval->format("%s second").($interval->s > 1 ? 's':'');
} else {
return 'milliseconds';
}
}

Categories