How to subtract a decimal time from a clock time in PHP - php

I have the following PHP script:
<?php
$clockTime = "10:00 AM";
$decimalTime = "0.75"; // represents time in hours in decimal format
echo date( 'g:i A', strtotime( strtotime( $clockTime ) . ' -'.$decimalTime.' hours' ) ); // returns "7:00 PM" when I need it to return "9:15 AM"
?>
How can I get the script to properly calculate and return 9:15 AM rather than 7:00 PM?

strtotime returns the time in seconds, so you need to convert the decimal time in seconds:
<?php
date( 'g:i A', strtotime( $clockTime ) - $decimalTime * 60 * 60 ) );
?>
However, this will not work when daylight saving (DST) comes into play. Especially if your code will be run in different countries, use timezones and the DateTime-API:
<?php
$date = new \DateTime($clockTime); // This uses the system default timezone where the server is located
$date->sub(new \DateInterval('PT' . ((int) $decimalTime * 60 * 60) . 'S'));
echo $date->fomat('g:i A');
?>

Related

converting Date and Seconds

While using strtotime function , if i am giving +48 day i am not sure whether is working fine or not ?
<?php
date_default_timezone_set('Asia/Kolkata');
$Seconds = 8604800 ;
$At = "2018-11-28 12:16:19";
echo date('Y-m-d H:i:s',strtotime("+48 day",strtotime($tAt)));
?>
strtotime expects the first parameter to be a valid time string. You are providing the number of seconds. Try -
echo $requestValidTill = date('Y-m-d H:i:s',strtotime("+$resetPasswordDurationInSeconds SECONDS",strtotime($requestAt)));
Output
2018-12-05 12:16:19
strtotime()
Working code
if you have PHP 5.3+ you can use the following lines of code
$requestAt = "2018-11-28 12:16:19";
$resetPasswordDurationInSeconds = 604800 ; //60 * 60 * 24 * 7 ( +7 days in seconds )
$date = new DateTime($requestAt );
$date->add(new DateInterval('PT'.$resetPasswordDurationInSeconds.'S')); // adds 604800 secs
echo date('Y-m-d H:i:s', $date->getTimestamp());
Your just need to add seconds in strtotime
<?php
$requestAt = strtotime("2018-11-28 12:16:19");
$requestAt += 604800;
echo date('Y-m-d H:i:s', $requestAt);
?>
Live Demo

How can I test for time differences in PHP - from times I get from a REST API as a string in the following format?

the format is 02.02.2018 12:00 EST and 02.02.2018 15:00 EST so then I can get 3 hours. I've tried several methods but no luck
$sTimeStr = strtotime('02.02.2018 12:00 EST');
$eTimeStr = strtotime('02.02.2018 15:00 EST');
$cur_time = strtotime( date( "m.d.Y h:i T", time() ));
if( $cur_time > $sTimeStr && $cur_time < $eTimeStr ){
//code to display
}
strtotime returns time in unix timestamp format so you can just subtract the two numbers to get the difference.
$t1 = "02.02.2018 12:00 EST";
$t2 = "02.02.2018 15:00 EST";
$time1 = strtotime($t1);
$time2 = strtotime($t2);
$diff = ($time2 - $time1);
$diff_in_hours = ($diff/60)/60;// $diff_in_hours = 3
$sysdate = date( 'm.d.Y', time() );
$systime = get_date_from_gmt( date( 'H:i', time() ), 'H:i' );
I ended up splitting date and time for better control

Converting Timezones from UTC

I'm having trouble converting timezone's from UTC to a user selected timezone. The problem seems to be Daylight Savings Time.
Here is an example I just coded.
<?php
date_default_timezone_set("UTC");
$timezone = -5.0;
$timestamp = time();
$local_time = $timezone * 3600 + $timestamp;
echo date( "m/d/Y - h:i A", $local_time );
?>
When I run the test file it returns 07/21/2014 - 04:29 PM. The current time is actually 5:29. The problem is Daylight Savings Time, where our clocks are turned back an hour.
How can I remedy this problem, or is there a more effective method for adjusting timestamps?
Easiest solution I see is making users select whether DST is currently in effect where they live, as not every country/timezone uses DST. If it is in effect then simply modifying the $timezone variable to +1 would suffice, but would require each user to manage whether DST is in effect or not.
Thank-you in advance.
EDIT:
I tried using DateTime but it was still off...
<?php
$timestamp = time();
echo 'Unix timestamp: ' . $timestamp . "<br/>";
echo 'Unix date: ' . date( "m/d/Y - h:i A", $timestamp ) . "<br/><br/>";
$dt = date_create_from_format('U', $timestamp);
date_timezone_set($dt, new DateTimeZone('America/New_York'));
$adjusted_timestamp = date_format($dt, 'U') + date_offset_get($dt);
echo 'America/New_York: ' . $adjusted_timestamp . "<br/>";
echo 'America/New_York: ' . date( "m/d/Y - h:i A", $adjusted_timestamp );
?>
The results were off by +2 hours. Returns 7:47 PM, it is currently 5:47 PM.
Unix timestamp: 1405979278
Unix date: 07/21/2014 - 11:47 PM
America/New_York: 1405964878
America/New_York: 07/21/2014 - 07:47 PM

find the closest next hour

how can I find the next closest hour in php
so for example if current time is 4:15 the next hour will be 5, etc
$dateString = 'Tue, 13 Mar 2012 04:48:34 -0400';
$date = new DateTime( $dateString );
echo $date->format( 'H:i:s' );
gives me the time from the string and I want to expand on that and get the next closest hour
$nextHour = (intval($date->format('H'))+1) % 24;
echo $nextHour; // 5
Here we go:
<?php
echo date("H:00",strtotime($date. " + 1hour "));
?>
Can you just take pieces (hours, minutes, seconds) and get the next hour?
$dateString = 'Tue, 13 Mar 2012 04:48:34 -0400';
$date = new DateTime( $dateString );
echo $date->format( 'H:i:s' );
echo "\n";
$nexthour = ($date->format('H') + ($date->format('i') > 0 || $date->format('s') > 0 ? 1 : 0)) % 24;
echo "$nexthour:00:00";
Supply any eligible date() to:
function roundToNextHour($dateString) {
$date = new DateTime($dateString);
$minutes = $date->format('i');
if ($minutes > 0) {
$date->modify("+1 hour");
$date->modify('-'.$minutes.' minutes');
}
return $date;
}
<?php
$dateString = 'Tue, 13 Mar 2012 04:48:34 -0400';
$date = new DateTime( $dateString );
$date->modify('+1 hour');
echo $date->format('H:i:s').PHP_EOL;
// OR
echo date('H:i:s', strtotime($dateString) + 60 * 60).PHP_EOL;
As I just needed something similar (next full hour) here my solution:
$now = time();
$nextFullHour = date(DATE_ATOM, $now + (3600 - $now % 3600));
By replacing the 3600 e.g. with 60 you get the next full minute...
You can also replace the $now with any other timestamp if you do not need it relative to the current time.
That is my solution:
$dateTime = new \DateTime();
$dateTime->add(new \DateInterval('PT1H'))
->setTime($dateTime->format('H'), '00');
Nobody else used this one so I figured I'd drop it here, simplest one I saw above for an actual timestamp, not just the hour itself.
$now = ''; // empty uses current time, or you can insert a datetime string
$next_hour = date( 'Y-m-d H:00:00', strtotime( $now . ' +1 hour' ) );
try it for current time, if you need put second argument to date function
<?php echo date('H')+1; ?>
very nice stuff
One more:
$current_datetime = new DateTimeImmutable();
$next_full_hour_datetime = $current_datetime
->modify(
sprintf(
'+%d seconds',
3600 - ($current_datetime->getTimestamp() % 3600)
)
);
A little late to this party, but here's a more flexible function to round up a dateTime object by any interval in minutes. You pass in your dateTime object and a rounding interval in minutes, so for an hour you'd just pass in 60, etc.
public function round_up_time( $datetime, $rounding_interval ) {
// get total minutes from the start of the day
$minutes = ( intval( $datetime->format( 'H' ) ) * 60 ) + ( intval( $datetime->format( 'i' ) ) );
// round up the minutes based on the interval we are rounding to
$rounded_minutes = ( intval( $minutes / $rounding_interval ) + 1 ) * $rounding_interval;
// reset our dateTime to the very start of the day
$datetime->setTime( 0, 0 );
// then increase the dateTime by the rounded minutes value
$datetime->modify( '+ ' . $rounded_minutes . ' minutes' );
}
To get the next closest full hour in DateTime:
$date = new DateTime('+1 hour'); //set the next hour
$date->setTime($date->format('H'), '00', '00'); //keep the next hour, set minutes to 00 and seconds to 00

HH:MM to seconds

I'm using an API function that returns an estimated time of arrival in hh:mm left, ie. 0:31 left until arrival.
What I'm trying to do is add the returned hh:mm to the current time, so the end result is the estimated time of arrival in UTC.
I currently have a very simple script that works as-is, but as the API function is formatted hh:mm and strtotime doesn't seem to recognize adding or subtracting anything but integers, this won't work if in the following script you replace +07 with +hh:mm.
<?php
$time = strtotime("now +07 hours");
print gmdate('H:i T', $time);
?>
So my end outcome should be hh:mm of the ETA in UTC.
A more flexible way:
<?php
function getETA($arrival, $timezone='UTC', $format='H:i T')
{
list($hours,$minutes) = explode(':', $arrival);
$dt = new DateTime('now', new DateTimeZone($timezone));
$di = new DateInterval('PT'.$hours.'H'.$minutes.'M');
$dt->add($di);
return $dt->format($format);
}
?>
Usage:
<?php
echo getETA('07:10');
echo getETA('07:10', 'America/New_York', 'h:i a T');
?>
Example Output:
23:56 UTC
07:56 pm EDT
If you change your strtotime parameter to now +07 hours, +06 minutes you should be able to add them. To get hours and minutes separate, just use explode(':', $returnedString)
$returnedString = '07:06';
$returnedTime = explode(':', $returnedString);
$time = strtotime("now +{$returnedTime[0]} hours, +{$returnedTime[1]} minutes");
// Or this
// $time = strtotime('now +' . $returnedTime[0] . ' hours, +' . $returnedTime[1] . ' minutes');
print gmdate('H:i T', $time);
<?php
$str = "17:26";
$secs = (substr($str, 0, 2) * 3600) + (substr($str, 3, 2) * 60);
echo $secs;
// Output: 62760
?>

Categories