Convert DateInterval object to seconds in php - php

$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
How do i convert the above $interval to seconds in php

Another way to get the number of seconds in an interval is to add it to the zero date, and get the timestamp of that date:
$seconds = date_create('#0')->add($interval)->getTimestamp();
This method will handle intervals created via the DateInterval contructor more or less correctly, whereas shiplu's answer will ignore years, months and days for such intervals. However, shiplu's answer is more accurate for intervals that were created by subtracting two dates. For intervals consisting only of hours, minutes and seconds, both methods will get the correct answer.

There is a function format for this. But it wont return the number of seconds. To get number of seconds you use this technique
$seconds = abs($datetime1->getTimestamp()-$datetime2->getTimestamp());
If you really want to use $interval you need to calculate it.
$seconds = $interval->days*86400 + $interval->h*3600
+ $interval->i*60 + $interval->s;
Here
86400 is the number of seconds in a day
3600 is the number of seconds in an hour
60 is the number of seconds in a minute

I would only add to shiplu's answer:
function dateIntervalToSeconds($interval)
{
$seconds = $interval->days*86400 + $interval->h*3600
+ $interval->i*60 + $interval->s;
return $interval->invert == 1 ? $seconds*(-1) : $seconds;
}
To handle negative intervals.
Note that - contrary to Brilliand's answer - The code above will consider correctly years, months and dates. Because $interval->days is an absolute value ($interval->d is relative to the month).
EDIT: this function is still not correct, as pointed out by #Brilliand. A counter-example is
new DateInterval('P4M3DT2H');
It doesn't handle months well.

Related

Display time with 1 zero when seconds is less or equal to 60 seconds

I'm displaying videos and I want to show the duration. Im using the following:
echo ltrim(date('i:s', $vduration), '0')
//result
5:40
But, if the video is 40 seconds only. The formula doesn't work. It shows
:40
Basically, if the video is less then 60 seconds, it should show 1 zero only (not 2), like so:
0:40
Is there a magic formula for this or do I need to use conditions to check if less or equal to 60 seconds?
Instead of date(), use printf() to format the numbers the way you wan.
$minutes = date('i', $vduration);
$seconds = date('s', $vduration);
printf("%d:%02d", $minutes, $seconds);
%d will format a number with no leading zeroes, %02d will format a number in 2 digits with leading zeroes.
A date is poorly suited to represent a time interval. The DateInterval class is better suited. The date interval format method can also represent minutes without leading zeros.
//example to create a date interval
$timeStart = date_create_from_format('!','');
$timeEnd = date_create_from_format('!i:s','00:07');
$interval = $timeStart->diff($timeEnd);
//output
echo $interval->format('%i:%S'); //0:07
If the minutes and seconds are given, a date interval can also be created directly.
$minute= 1;
$second = 40;
$interval = new DateInterval('PT'.$minute.'M'.$second.'S');

Converting a Total Time to Seconds

I'm totalling up time like so.
$totalTimeDiff = new DateTime("#0");
foreach($dbrecords as $row)
{
$timeDiff = date_diff( ... two datetimes from my database ... )
$totalTimeDiff->add($timeDiff);
}
So $totalTimeDiff is a DateTime object with the sum of all of the time differences added together (so a sum of all of the durations). How can I get the total time in seconds?
Why not keep it simple?
$totalseconds=0;
foreach($dbrecords as $row)
$totalseconds+=(UNIX_TIMESTAMP(second_datetime)-UNIX_TIMESTAMP(first_datetime));
use strtotime function
echo strtotime('01:00:00') - strtotime('TODAY');
$totalTimeDiff->format('U');
Taking moonwave99's advice, I used DateInterval (can't remember why I went with DateTime for that in the first place, possibly a workaround for something at another stage of the project) and computed the seconds by adding each value to the total after converting it to seconds (converting hours and minutes to seconds and summing them up). I did this by using the DateInterval class's seconds property as well as the following function to convert a DateInterval to seconds (Note: only accounted for days, hours, minutes, and seconds for my specific case as there's no chance the amount will exceed one month):
function convertDateIntervalToSeconds($dateInterval)
{
$days = $dateInterval->d * 24 * 60 * 60;
$hours = $dateInterval->h * 60 * 60;
$minutes = $dateInterval->i * 60;
$seconds = $dateInterval->s;
return $hours + $minutes + $seconds;
}

php date_diff in hours

How is it possible to make the code below convert days in hours?
$timestart = date_create('02/11/2011' . $row->timestart); //$row->timestart returns time in 00:00:00 format
$timestop = date_create('02/11/2011' . $row->timestop); //$row->timestop returns time in 00:00:00 format
date_add($timestop, date_interval_create_from_date_string('2 days')); //add 2 days
$date_diff = date_diff($timestart, $timestop);
echo "Timespan: ";
echo $date_diff->format('%h hours');
echo "<br />";
How can I get the hours:minutes:seconds elapsed? I'm trying to stay with the date_diff function.
The result of date_diff() is an object of DateInterval class. Such object has a very useful property - $days: it's total number of days between the starting and the ending dates. Besides, it stores (as its public properties) the difference in hours, minutes and seconds.
So, I suppose, what you need is just extract values of these properties from $date_diff variable, then add 24*$days to the hours number. ) All this can be wrapped into a simple function:
function hms_date_diff(DateInterval $date_diff) {
$total_days = $date_diff->days;
$hours = $date_diff->h;
if ($total_days !== FALSE) {
$hours += 24 * $total_days;
}
$minutes = $date_diff->i;
$seconds = $date_diff->s;
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
As for DateDiff::format, the doc says...
The DateInterval::format() method does not recalculate carry over
points in time strings nor in date segments.
The DateInterval object, returned by date_diff stores each period of time separately, seconds, minutes, hours, days, months and years.
Since the difference is 2 days, the hours property is 0, which is what you get.

How to get current time elapsed percentage of today? [duplicate]

This question already has answers here:
Work out the percentage of the day that has elapsed
(5 answers)
Closed 9 years ago.
Im trying to get the current time elapsed percentage of todays time. It can be either javascript or php. How can I do that ?
Use a Date object and some arithmetic. Convert the components of the current day into a equivalent unit (such as seconds), find their sum, and divide that by the number of that unit per day.
For example, the following is a solution in JavaScript.
var d = new Date();
var pctDayElapsed = (d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds() + d.getMilliseconds()/1000)/86400;
Note that this approach piggybacks on the browser's localization. Your result will depend on the browser's timezone.
I would use the current time to calculate the number of seconds that has elapsed today and then divide that by 86400 (the number of seconds in a day), and of course multiply that by 100 to get it from decimal to percent.
Here is an answer in PHP:
$now=time();
$today=strtotime(date("m/d/Y"));
$seconds=$now-$today;
$day=24*60*60;//seconds in a day;
$percent=$seconds/$day*100;
OR
$hours=date('G')*60*60;
$minutes=date('i')*60;
$seconds=date('s');
$day=24*60*60;//seconds in a day;
$percent=($hours+$minutes+$seconds)/$day*100
<?php
$timestamp = time();
$hours = intval(date("G", $timestamp));
$minutes = intval(date("i", $timestamp));
$seconds = intval(date("s", $timestamp));
$proportion_elapsed = ($hours * 60 * 60 + $minutes * 60 + $seconds) /
(24 * 60 * 60);
printf("%0.4F of the day has elapsed.", $proportion_elapsed);
?>
This works as long as there are 86,400 seconds in a day, which may not be true due to Daylight Savings time or leap seconds.
Round down to the beginning of the day by dividing the current time by 86400, then multiply that integer value by 86400. Then take the difference of the current time (in seconds of course) and then divide 86400 into it. Lastly, multiply by 100.
Edit: mod works more efficiently
Pseudocode:
MidnightDays = (TimeInSeconds % 86400) * 86400;
Percentage = (TimeInSeconds - MidnightDays) / 86400 * 100;

How to return the amount of years passed?

My friend and I are working on a fairly basic uptime script for an IRC Bot.
Here's our code:
function Uptime()
{
global $uptimeStart;
$currentTime = time();
$uptime = $currentTime - $uptimeStart;
$this->sendIRC("PRIVMSG {$this->ircChannel} :Uptime: ".date("z",$uptime)." Day(s) - ".date("H:i:s",$uptime));
}
$uptimeStart is set immediately when the script runs, as time();
for some reason when I execute this function, it starts at 364 days and 19 hours. I can't figure out why.
Your $uptime is not a timestamp as should be used in date(), but a difference in time. You have an amount of seconds there, not a timestamp (that corresponds with an actual date.
just use something like this to cacluate (quick one, put some extra brain in for things like 1 day, 2 hours etc) ;)
$minutes = $uptime / 60;
$hours = $minuts/60 ;
$days = $hours / 24
etc
If you have 5.3 or above, use the DateTime and DateInterval classes:
$uptimeStart = new DateTime(); //at the beginning of your script
function Uptime() {
global $uptimeStart;
$end = new DateTime();
$diff = $uptimeStart->diff($end);
return $diff->format("%a days %H:%i:%s");
}
You won't get anything meaninful by calling date() on that time difference. You should take that time difference and progressively divide with years, months, days, hours, all measured in seconds. That way you'll get what the time difference in those terms.
$daySeconds = 86400 ;
$monthSeconds = 86400 * 30 ;
$yearSeconds = 86400 * 365 ;
$years = $uptime / $yearSeconds ;
$yearsRemaining = $uptime % $yearSeconds ;
$months = $yearsRemaining / $monthSeconds ;
$monthsRemaining = $yearsRemaining % $monthSeconds ;
$days = $monthsRemaining / $daySeconds ;
.. etc to get hours and minutes.
date() function with second argument set to 0 will actually return you (zero-date + (your time zone)), where "zero-date" is "00:00:00 1970-01-01". Looks like your timezone is UTC-5, so you get (365 days 24 hours) - (5 hours) = (364 days 19 hours)
Also, date() function is not the best way to show the difference between two dates. See other answers - there are are already posted good ways to calculate difference between years

Categories