1

I store the dates in my database in DATETIME type, looking as: Y-m-d H:i:s

What I want to achieve is to return the date from the database in the local time of the user. For example, if the user is in France, I will return his timezone. Is it possible to achieve this without storing the timezone of the user? Or if it is possible somehow else, and the storing format in the database needs to be changed, then I can do that. But, I am trying to achieve this without storing the user's timezone.

3 Answers 3

2

Store times in UTC in the database, and then do the timezone localization in your application. You will need to know the user's timezone, though.

4
  • ... and take into account daylight savings.
    – Ed Heal
    Apr 13, 2012 at 15:53
  • @EdHeal: That's correct. I believe DST is accounted for already in the offset if you use the getTimezoneOffset() method in JS to report back to the server.
    – FtDRbwLXw6
    Apr 13, 2012 at 16:16
  • It does assume that the machine has its clock set correctly! Public machines (like this one) is out by 3 hours and 22 minutes!
    – Ed Heal
    Apr 13, 2012 at 16:26
  • @EdHeal: Of course, but I'm not sure there's a more accurate way without prompting the user to enter it manually (and if this is for a web app, that could be preferable, since you could save it in the user's preferences).
    – FtDRbwLXw6
    Apr 13, 2012 at 17:50
1

Well, the only way I can think of doing it without asking the user for their timezone is this:

<p>The time is: <span id="time" data="<?php echo strtotime($time_from_db); ?>"></span></p>
<script type="text/javascript">
    (function () {
        var t = document.getElementById('time'), d = new Date();
        d.setTime(t.getAttribute("data"));
        t.innerHTML = d;
    })();
</script>

This passes the datetime as a timestamp, which JS then applies locale (including timezone) to.

2
  • Do you suggest to store the time in the db as timestamp?
    – Darko
    Apr 13, 2012 at 16:00
  • I like to use timestamps, but it doesn't actually make any difference unless you enter the value as a number rather than a formatted date. Apr 13, 2012 at 16:14
1

If you store dates in GMT, then you can present them to the user on their timezones.

EDIT:

 date_default_timezone_set('UTC');
 $today = getdate();
 print_r($today);

Check this: php convert datetime to UTC and this: Convert UTC dates to local time in PHP and this: http://www.php.net/manual/en/function.gmdate.php

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.