I am adding auction-based data to my system. For example:
user's timezone is : `America/Denver`
auction start time is : Thu, 21 Jun 2012 03:46:22 AM
auction period : 1 day.
auction end time : Fri, 22 Jun 2012 03:46:22 AM
I store all these information as it is in my DB (i.e. all stored time based on user's timezone).
Now I want the actual difference between end time and current time (of America/Denver timezone).
I used DateTime()
functions
so even I don't convert the timezone; it returns same difference (and that is wrong too).
My PHP code is below; you can also find it at CodePad
$end_time = 'Fri, 22 Jun 2012 03:46:22 AM';
$tz = 'America/Denver';
dateDifference($end_time,$tz);
function dateDifference($end, $tz = NULL)
{
$owner_tz = new DateTimeZone($tz);
//var_dump($owner_tz->getName());
$from = new DateTime("now", new DateTimeZone('GMT'));
$from ->setTimeZone($owner_tz);
$to = new DateTime($end,new DateTimeZone('GMT'));
/* @Note:I have commented below setTimeZone() because I have already stored
* `end time` as per user's timezone, So I dont need to convert it again
* into user's timezone.you can un-comment below line.
* it doesn't affect the results anyways.
*/
//$to ->setTimeZone($owner_tz);
//procedural style using date_diff()
$interval = date_diff($from, $to);
var_dump($interval);
// OO style using dateTime::diff()
$interval = $from->diff($to);
var_dump($interval);
}
Returns:
object(DateInterval)[4]
public 'y' => int 0
public 'm' => int 0
public 'd' => int 0
public 'h' => int 16
public 'i' => int 40
public 's' => int 24
public 'invert' => int 0
public 'days' => int 6015
References:
On the following lines you're basically saying that the end date is in GMT while it should be in America/Denver time:
Then you intent to convert it to America/Denver time but since you created the date using the GMT timezone this would have been wrong anyway.
This will create the end date using the users timezone which is probably what you are looking for:
I got the solution, so i would like to share
Actually I have set default timezone in
config.inc.php
file as belowdate_default_timezone_set('America/Los_Angeles');
then I check the current time and timezone of MySQL server from phpmyadmin with below query
This return the
OFFSET
value +05:30solution steps:
First I changed the timezone of mySQL Server to GMT/UTC +00:00 ( I have super privilage on mySQL server)
start_date = NOW()
( column datatype:DATETIME
)Now there is 2 way to get date and time as per user's timezone (
America/Denver
)first method ( using PHP DateTime)
second method (using MySQL UNIX_TIMESTAMP)
Note : dont change
start_date
to timestamp withstrtotime()
. It will return different value from theUNIX_TIMESTAMP()
i.e.