The situation
I've got two timestamps.
One with the start time and one with the end time.
The start time is: 04:43:37
The end time is: 11:59:59
Now I am trying to get the difference between the dates like this:
//define timestamps
$start_time = 1297698217;
$end_time = 1297724399;
$time_diff = $end_time - $start_time;
//display times and difference
echo
'<b>Start time:</b> ' . date('d-m-Y h:i:s', $start_time) . '<br />' .
'<b>End time:</b> ' . date('d-m-Y h:i:s', $end_time) . '<br />' .
'<b>Time difference::</b> ' . date('h:i:s', $time_diff);
The result
Start time: 14-02-2011 04:43:37
End time: 14-02-2011 11:59:59
Time difference: 08:16:22
The problem
Now the problem is that the result should be 07:16:22. I've tried this with different times, but every time I'm getting the same result. One hour too much difference.
Is there an expert willing to help?
The last one should be gmdate instead of date:
'<b>Time difference::</b> ' . gmdate('h:i:s', $time_diff);
date adjusts for your current locale, which appears to be GMT+1. gmdate does not make that adjustment.
I'm assuming that you're only planning to use this for time differences less than 24 hours.
You're asking it to turn 1970-01-01 07:16:22 into a time string for display - there are going to be differences based on your time zone.
To make it a GMT date use gmdate() but this will still cause you issues when time differences get >24 hours.
Related
The following code helps me project data from a database onto our internal adminsite for the current day.
Since we're in multiple time zones, we use UTC time for basic time function, but since our office is in California, we want the date to actually be = ($date)'hours' - 8, because PST is 8 hours behind.
We use the following logic to show the "previous day" if it's "a day ahead" UTC time but the same day our time, which works great, however, on the last day of the month at 4 PM, all of our data is hidden.
<?php
$date = getDate();
if ($date['hours'] < 8) {
$dateDay = $date['mday']-1;
} else {
$dateDay = $date['mday'];
}
$dateMonth = $date['mon'];
// last day of month
// $dateMonth = $date['mon'] - 1;
$dateYear = $date['year'];
$dateTime = $dateYear . "-" . $dateMonth . '-' . $dateDay . ' 08:00:00';
So, this 'if' function works great to show the true "day." What it says is, if the UTC hour < 8, then it's actually yesterday, as 3 AM UTC time is actually 7 PM the day before PST.
What I was wondering is if there's a way to track "month hours", so I could use the same 'if' function that reads "if we're less than 8 UTC hours into the month, it's actually still last month."
That way it'll work regardless of whether the month has 28, 30 , or 31 days. Does such logic exist?
I think its the best way to deal with it :
<?php
$date = new DateTime('2016-08-08', new DateTimeZone('UTC'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('America/Los_Angeles'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
You can use DateTime::sub or DateTime::modify method which will keep correct month for you:
$now = new DateTime(getDay()); // supposing getDate() returns something that can be parsed with DateTime constructor
// Unless using DateTimeImmutable, cloning is needed to prevent altering the original object
$min = clone ($now);
$min->modify('-8 hours');
// alternatively $min->sub(new DateInterval('PT8H'));
if ($now->format('m') !== $min->format('m')) {
// month differs
}
I need to get the milliseconds of exactly on week ago.
I tried this:
$this->weekDate = strtotime("-1 week");
echo($this->weekDate);
it returns:
1422536434
which according to this conversion tool:
http://www.fileformat.info/tip/java/date2millis.htm
is
Samstag, 17. Januar 1970 11:08 Uhr GMT
Anybody an idea what is wrong?
The above code is printing the time in seconds Use the code below
$this->weekDate = strtotime("-1 week");
echo($this->weekDate * 1000);
The output of the above code will be
1,422,536,434,000
Hope this helps you
It might be because of the timezones (you didn't mention when you were trying to calculate the 1 week ago so it's hard to tell what output you expected).
Try this:
//get current time
$now = time();
//output in human readable format
echo 'now: ' . date('r', $now) . '<br />';
//calculate same time 1 week ago
$this->weekDate = strtotime("-1 week", $now);
//output it to compare
echo '1 week ago: ' . date('r', weekAgo));
I’m having an issue calculating the difference between two time. Here’s my code.
<?php
$Now = date('h:i:s');
echo 'Now is: '. $Now . '<br>';
$time1 = strtotime('01:22:24');
$time2 = strtotime('01:28:24');
$diff = $time2 - $time1;
echo 'Time 1: '.date('h:i:s', $time1).'<br>';
echo 'Time 2: '.date('h:i:s', $time2).'<br>';
if($diff){echo 'Difference: '.date('h:i:s', $diff);
}else{echo 'No Difference.';}
?>
What it outputs is
Now is: 03:07:01
Time 1: 01:22:24
Time 2: 01:28:24
Difference: 06:06:00
The time “Now is:” is the correct time. The timezone in my php.ini is set to US/Central and I’ve even tried America/Chicago but no help. I’m running PHP 5.3.5 with apache 2.0
Any ideas? Thanks.
The date function takes a UNIX timestamp as its second argument. UNIX timestamps are seconds since January 1, 1970. So when you pass in $diff as the second argument to date, it is interpreting that as seconds since January 1, 1970 and then displaying the hour, minute and date components of that date!
You should look into using http://us3.php.net/manual/en/class.datetime.php and http://us3.php.net/manual/en/datetime.diff.php instead. Here is the code using these classes:
<?php
$time1 = new DateTime('01:22:24');
$time2 = new DateTime('01:28:24');
if ($time1 == $time2) {
echo 'No Difference.';
} else {
$diff = $time2->diff($time1);
echo 'Difference: ' . $diff->format('%H:%I:%S');
}
You're trying to output a difference that's expressed in seconds as a date value.
The difference should be expressed as:
if($diff){echo 'Difference: '.$diff . " seconds";
The value of $diff is a number of seconds. When you use date however you're localising the time which in this case is adding 6 hours.
Use gmdate instead.
http://uk1.php.net/gmdate
if($diff){echo 'Difference: '.gmdate('h:i:s', $diff);
may be you know why this doesnt work (trying to receive timeStamp in another timeZone):
$from_zone = 'Europe/Kiev';
$to_zone = 'US/Eastern';
$stamp = 1383897599;
$from_tz = new DateTimeZone($from_zone);
$to_tz = new DateTimeZone($to_zone);
$dateTime = new DateTime(null, $from_tz);
$dateTime->setTimestamp($stamp);
$dateTime->setTimeZone($to_tz);
$new_stamp = $dateTime->getTimestamp();
echo $new_stamp;
return initial timeStamp instead of the new one, what im doing wrong ? :\
UNIX timestamps are by definition based on UTC. A timestamp will always return same date/time regardless of time zone.
From Wikipedia:
Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of Thursday, January 1, 1970
Timestamp is a number of seconds passed since 1 January 1970 00:00:00 UTC. Changing timezones does not affect that value, as well as time() function returns the same value independently of the set timezone.
If you need different timestamps, try using strtotime($dateString), as it is affected by timezones, like this:
date_default_timezone_set('Europe/Kiev');
$date = date('Y-m-d H:i:s');
echo $date . ' - ' . strtotime($date) . '<br />';
date_default_timezone_set('US/Eastern');
echo $date . ' - ' . strtotime($date) . '<br />';
which prints:
2013-11-08 20:48:47 - 1383936527
2013-11-08 20:48:47 - 1383961727
I'm trying to do some very basic time math - basically, given inputs of time and distance, calculate the speed. I chose to use strtotime() to convert the time inputs into seconds - but I'm getting some bizarre results.
For example, given this sample program:
<?php
$t1 = strtotime("3:15:00",0);
$t2 = strtotime("1:00:00",0);
$t3 = strtotime("2:00:00",0);
$t4 = strtotime("9:00:00",0);
echo $t1 . "\n";
echo $t2 . "\n";
echo $t3 . "\n";
echo $t4 . "\n";
?>
Why do I get these results?
$ php test.php
-56700
-64800
-61200
-36000
Update:
Since no one said it explicitly, let me explain the bug in the above function. I had assumed that passing a time of zero to strtotime() would cause it to generate time stamps derived from midnight, 12/31/1969, UTC - which sounds odd, but would work for my purposes.
What I hadn't counted on was that strtotime() takes time zones into account when converting strings, and my server is apparently 5 hours behind UTC. On top of that, because of the time zone shift, PHP then interprets the times as relative to the day before the epoch which means it is interpreting my times as occurring relative to December 30th, 1969 instead of the 31st, resulting in negative numbers...
It appears that Eugene is correct - if I want to calculate just the elapsed time, I can't use the built in time functions.
If you want to do something like that, I think you want to just do some math on the time strings themselves and convert them to a number of seconds, like this:
<?php
function hmstotime($hms)
{
list($hours, $minutes, $seconds) = explode(":",$hms);
return $hours * 60 * 60 + $minutes * 60 + $seconds;
}
?>
Apparently with just bare times PHP is assigning the date December 31, 1969. When I ran this:
echo date('F j, Y H:i:s', $t1) . "\n";
echo date('F j, Y H:i:s', $t2) . "\n";
echo date('F j, Y H:i:s', $t3) . "\n";
echo date('F j, Y H:i:s', $t4) . "\n";
I got this:
December 31, 1969 03:15:00
December 31, 1969 01:00:00
December 31, 1969 02:00:00
December 31, 1969 09:00:00
Remember that strtotime returns a UNIX timestamp, which is defined as the number of seconds since January 1, 1970. By definition a UNIX timestamp refers to a specific month/day/year, so despite the name strtotime is not really intended for bare times without dates.
Because strtotime() outputs the number of seconds relative to the second argument (in your case, the Unix epoch (December 31, 1969 19:00:00)).
The negative numbers is expected because "3:15:00" is 56700 seconds before the Unix epoch.
Try it without the second parameter. That's supposed to be a timestamp for the returned time to be relative to. Giving it 0 means you're asking for a timestamp relative to the Unix epoch.
In response to your comment:
It's not documented functionality, but I use strtotime("HH:MM") all the time, and it returns a timestamp relative to the current time. I guess if you want to be sure though, you could do this:
strtotime("3:15:00",time());
strtotime() without a second argument gets the time from the supplied string and fills in the blanks from the current date:
echo date('Y-m-d H:i:s', strtotime("3:15:00"));
-> 2009-06-30 03:15:00
With a second argument it calculates the date relative to the second argument:
echo date('Y-m-d H:i:s', strtotime("3:15:00", 0));
-> 1970-01-01 03:15:00
To calculate the difference between two timestamps in seconds, you can just do this:
echo strtotime("3:15:00") - strtotime("3:00:00");
-> 900
Edit: Of course taking into account which is the bigger number:
$t1 = strtotime("3:15:00");
$t2 = strtotime("3:30:00");
$diff = max($t1, $t2) - min($t1, $t2);
$diff = abs($t1 - $t2);
Or something of that nature...