2

I have a page that shows future events along with the date (server time). I need some method to display the date in user time.

Example:
Oct, 26 13:48:23 (server)
Oct, 26 14:48:23 (user time (UTC +1)) -> event info

What I have so far:

<?php
    $sql=mysql_query("SELECT * FROM table") or die("Come back later");
    while($row=mysql_fetch_array($sql)) {
        echo date('M, d H:i:s', strtotime ($row['date'])).' -> '.$row['info'];
    }
?>

With the diffence I want to detect user timezone.

Thank you.

EDIT I know I should not be using mysql_*

2

3 Answers 3

1

If you're ok with doing the conversion to the user's time zone in JavaScript, you could do the following:

PHP

<?php
    $sql=mysql_query("SELECT * FROM table") or die("Come back later");
    while($row=mysql_fetch_array($sql)) {
        echo '<span class="date">' . date('M, d H:i:s', strtotime ($row['date'])) . ' UTC</span> -> '.$row['info'];
    }
?>

JavaScript (With jQuery for Readability)

$(function(){
    $('.date').each(function(){
        var $this = $(this);

        // Parse the date string (the format you've given will 
        // work, and the added UTC above will give JavaScript 
        // some context)
        var dateVal = new Date($this.text());

        // JavaScript will convert it to the user's timezone when 
        // stringifying it (helped by the server timezone specified
        // in the PHP.
        $this.text(dateVal.toString()); 
    });
});

If you want to render the dates in the format: Oct, 26 13:48:23, you could do this:

var dateString = dateVal.toLocaleString();
var parts = /^\w+ (\w+ \d{1,2}) \d{4} (\d{2}:\d{2}:\d{2})/.exec(dateString);
dateString = parts[1] + ' ' + parts[2];

Then use $this.text(dateString); to inject it into the dom.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but how can I format the date, since I output it with PHP like this: Oct, 26 13:48:26
I edited the post to show you how to get the value you asked about :)
0

You need to create DateTime object from this date, and then apply DateTimeZone to that object.

Comments

0

You would need to get the timezone from the user.

You can accomplish this by offering a dropdown with timezones that the user can select and submit. To make this a little more user friendly you could use some of the geoip functions to detect country and region and then determine a default timezone for the user. Do keep in my that location by IP is not 100% accurate but is instead an educated guess as to where the user may be located.

Alternatively you can use ajax to send the timezone to the server and then update accordingly.

1 Comment

Alternatively you can use ajax to send the timezone to the server and then update accordingly. How can I do that?

Your Answer

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