简体   繁体   中英

DateTime won't change temporary

My whole site is:

date_default_timezone_set('Europe/London');

A user can select their timezone, and in the database it saves as 4.0 (for Dubai)

Now I wish to have so the timezone the user has chosen has an impact on the countdown, that exists on the site. The countdown looks like this:

    $today_date = new DateTime('now');  // now
    $final_date = new DateTime($date); // a date in the future
    $interval = $today_date->diff($final_date); // find the difference

    $time_left = $interval->format('starting in %d days, %h hours and %i minutes'); // display it

Above this, i did following:

        $userGMT = $user->get_gmt();
        date_default_timezone_set($userGMT);

Which does not work correct. It still counts down for Europe/London timezone, and not the one I have chosen.

I tried do echo date('H:i:s'); and can see by the time that the above has affected and it is showing the time for the timezone I have picked.

So that works, but dateTime('now'); doesnt?

What you want to do is add the $userGMT to your currentTime and then subtract your server time. So get the time in seconds then add $userGMT*60*60 - $yourTimeZone*60*60

When the date in the future is generated, it needs to be explicit about the applicable timezone. This demonstrates that the interval is independent of the host's timezone:

<?php
$date = '2012-04-19';   // date in the future
$user_tz = new DateTimeZone('Asia/Dubai');
foreach (array('Europe/London', 'America/Los_Angeles') as $tzname)
{
  date_default_timezone_set($tzname);
  $today_date = new DateTime('now');  // now
  $final_date = new DateTime($date, $user_tz); // future date with explicit tz
  $interval = $today_date->diff($final_date); // find the difference
  $time_left = $interval->format('start in %d days, %h hours and %i minutes');
  echo "$tzname:  $time_left\n";
}

Output:

Europe/London:  start in 0 days, 11 hours and 53 minutes
America/Los_Angeles:  start in 0 days, 11 hours and 53 minutes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM