Subtract Time String in PHP - php

Say I have the following as a string:
$timeLeft = 00:02:30
I want to be able to subtract 1 second, turning it into 00:02:29.
I have tried
$timeLeft - 1;
But it does nothing.
How can I make it so I can subtract seconds from a string?

You need to convert it to a time, subtract 1 second and reformat, e.g.:
$timeLeft = '00:02:30';
$time = DateTime::createFromFormat('H:i:s', $timeLeft);
$time->sub(new DateInterval('PT1S'));
$timeLeft = $time->format('H:i:s');
Below is dirty code that performs the transformation "manually" by converting the time into seconds in case PHP 5.3+ is not available. It'll certainly misbehave it the number of seconds subtracted is greater than the total.
$timeLeft = '00:02:30';
list($hours, $minutes, $seconds) = explode(':', $timeLeft);
$seconds += $hours*3600 + $minutes*60;
unset($hours, $minutes);
$seconds -= 1; //subtraction
$hours = floor($seconds/3600);
$seconds %= 3600;
$minutes = floor($seconds/60);
$seconds %= 60;
$timeLeft = sprintf("%'02u:%'02u:%'02u", $hours, $minutes, $seconds);

Using strtotime is a good practical solution, but you have to watch out for DST changes:
$tz = date_default_timezone_get(); // save old timezone
date_default_timezone_set('UTC'); // switch to UTC
echo date('H:i:s', strtotime($timeleft) - 1); // perform calculation
date_default_timezone_set($tz); // restore old setting

Related

Milliseconds format php

I got this number: 116041 (is it in milliseconds).
And i want to transform to something like this minuts:seconds:miliseconds
Theoretically that number should transform to something like: 1:56:xx
And I'm trying this code:
$diff = 116041;
$date = date("i:s:u",$diff);
echo $date;
But I'm getting this output:
14:01:000000
date() takes a timestamp integer. The value you are supplying equals Friday, January 2, 1970 8:14:01 AM. Notice the 14:01? That is what you are getting using date("i:s:u",$diff);
Go to Epoch Converter and enter 116041 into the field and you can see it for yourself.
This should be pretty simple math.
// Get the minutes (60000ms per minute)
$milliseconds = 116041;
$minutes = floor(116041 / 60000);
// Find the remaining milliseconds
$milliseconds = $milliseconds % 60000;
// Continue to seconds calculation...
In this case, the date or DateTime route is more complicated. Just do some simple math...
$s = 116041 / 1000;
printf("%d:%02.3f", intdiv($s, 60), fmod($s, 60));
You can try this method. please let me know if it of any help to you.
<?php
function formatMilliseconds($milliseconds) {
$seconds = floor($milliseconds / 1000);
$minutes = floor($seconds / 60);
$hours = floor($minutes / 60);
$seconds = $seconds % 60;
$minutes = $minutes % 60;
$milliseconds = $milliseconds % 1000;
$format = '%u:%02u:%02u.%02u';
$time = sprintf($format, $hours, $minutes, $seconds, $milliseconds);
return rtrim($time, '0');
}
echo formatMilliseconds(2000202123);
?>

PHP handle time value over 24:00H

I'm addditioning time value of a schedule.
When The value go over 24:00 I'm begining to have a problem..
Here is a simple example of what i'm trying to do.
$now = strtotime("TODAY");
$time_1 = strtotime('08:00:00') - $now;
$total = $time_1 * 5;
$total = $total + $now;
echo date('H:i', $total);
The echo value is 16:00:00
But it should be 40:00:00
24:00:00 + 16:00:00 = 40:00:00
So I understand that this is 1 day and 16 hours.
How can I echo 40:00:00
Below is your example code working the way you want.
As others have mentioned, you have to do the math yourself for cases like this.
<?php
$now = strtotime("TODAY");
$time_1 = strtotime('08:00:00') - $now;
$total = $time_1 * 5;
$secs = $total%60;
$mins = floor($total/60);
$hours = floor($mins/60);
$mins = $mins%60;
printf("%02d:%02d:%02d", $hours, $mins, $secs);
You can't. date() is intended to produce VALID date/time strings. 40 is not something that would appear in a normal time string. You'll have to use math to generate that time string on your own:
$seconds = $total;
$hours = $seconds % 3600;
$seconds -= ($seconds * 3600);
$minutes = $seconds % 60;
$seconds -= ($seconds * 60);
$string = "$hours:$minutes:$seconds";
The date function is for dates and times, not durations. Since the time is never "40:00", it will never return that string.
You can look into using the DateTimeInterface to get what you want, but it might be simpler just to do the math yourself.
$seconds = $total;
$minutes = (int)($seconds/60);
$seconds = $seconds % 60;
$hours = (int)($minutes / 60);
$minutes = $minutes % 60;
$str = "$hours:$minutes:$seconds";

Wrong time calculated having more than 30min

Im having a a bit strange problem, Im having this code and on output it adds always one hour more if the second time has 30 or more minutes.
$time1 = '12:00';
$time2 = '13:30';
list($hours, $minutes) = explode(':', $time1);
$startTimestamp = mktime($hours, $minutes);
list($hours, $minutes) = explode(':', $time2);
$endTimestamp = mktime($hours, $minutes);
$seconds = $endTimestamp - $startTimestamp;
$minutes = ($seconds / 60) % 60;
$hours = round($seconds / (60 * 60));
Whats happening here?
Remember the math. Rounding up everything in interval [0.5;1) equals to 1.
round(0.5) = 1
That's why you've +1 hour in case of minutes in [30;60].
Instead of using round use intval as $seconds / (60 * 60) expression always returns a float and we need only the integer part of that result

Php get how many days and hours left from a date

I have a created_at date saved liked this "2011-09-23 19:10:18" And I want to get the days and hours left
until the date is reached. How do I do that? and column name in database remain days automatically update daily with remain days, please solve this
PHP fragment:
<?php
//Convert to date
$datestr="2011-09-23 19:10:18";//Your date
$date=strtotime($datestr);//Converted to a PHP date (a second count)
//Calculate difference
$diff=$date-time();//time returns current time in seconds
$days=floor($diff/(60*60*24));//seconds/minute*minutes/hour*hours/day)
$hours=round(($diff-$days*60*60*24)/(60*60));
//Report
echo "$days days $hours hours remain<br />";
?>
Note the hour-round and no minutes/seconds consideration means it can be slightly inaccurate.
This should seed your endeavor.
getdate(strtotime("2011-09-23 19:10:18"))
Full conversion:
$seconds = strtotime("2011-09-23 19:10:18") - 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";
as of PHP 5.3.0 you could use build-in Date object:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
http://www.php.net/manual/en/book.datetime.php
it would be something like
echo $date = date("Y-m-d H:i:s");echo "\n";
$original=time($date);
$modified = "2011-09-23 19:10:18";
echo date("Y-m-d H:i:s",$modified);echo "\n";
The easiest way is improved answer from CountZero. I used this solution for counter for time remaining before expiration of offer. Addition to first three lines of CountZero code:
$days = $interval->d;
$hours = $interval->h;
$minutes = $interval->i;
$seconds = $interval->s;
And now, you can use string functions to moderate your return values, to merge all or add '0' or '00' in front of the values.
You can find current date and time using date() function and then subtract
$x = 2011-09-23 - current_date
this will give you no. of days left.
Do same with time as well ..
Hope this helps

How many seconds from mysql time format to now

I use this function to set a time date("Y-m-d H:i:s", strtotime("+2 minutes"). Now I want to compare that value with the current time to find the amount of seconds it's left.
For example compare: $next_action = 2011-01-16 18:03:00 and $now = 2011-01-16 18:01:23. To find the amount of seconds.
strtotime can convert mysql timestamps to unix timestamps. so you just convert both of them to UNIX timestamps and subtract one from other, and you'll get the difference in seconds.
$next_action = "2011-01-16 18:03:00";
$now = "2011-01-16 18:01:23";
echo strtotime($next_action)-strtotime($now);
Why did you convert them to "Y-m-d H:i:s" in the first place? Unix timestamps are much easier to work with.
$start_time = date("Y-m-d H:i:s", strtotime("+2 minutes"));
$time_diff = (time() - strtotime($start_time)); // difference in seconds
$seconds = $time_diff % 60;
$minutes = ($time_diff - $seconds) % (60 * 60);
$hours = ($time_diff - ($minutes * 60) - $seconds) / (24 * 60 * 60);
Untested, but it would probably go something like this.

Categories