0

here is a usefull function I have in my solution

public static function formatTime($time, $timezone)
{
    $timezone = new \DateTimeZone($timezone);
    $time = $time->setTimezone($timezone);
    return \Locale::getDefault() == 'fr' ? date('H:i', $time->getTimestamp() + $time->getOffset()) : date('g:i a', $time->getTimestamp() + $time->getOffset());
}

I store my dates in UTC for my items, and the container of these items has a defined timezone. With this function, I apply the timezone to all my items.

I need now to "translate" this function into a JS one doing exactly the same (in fact, my items are loaded by PHP but then new items directly come by JS and a need to apply homegeneously this same function in JS)

Currently, I've got this one (the previous one, without timezone considerations unfortunately):

        Twig.setFunction('format_time', function(value) {
        // http://stackoverflow.com/questions/5324178/javascript-date-parsing-on-iphone
        var arr = value.date.split(/[- :]/);
        var d = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);

        {% if app.request.getLocale() == "fr" %}
            return (d.getHours() < 10 ? '0' + d.getHours() : d.getHours()) + ':' + (d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes());
        {% else %}
            if (d.getHours() >= 12) {
                var hour = d.getHours() - 12;
                hour = hour < 10 ? '0' + hour : hour;
                var a = 'pm';
            } else {
                var hour = d.getHours();
                hour = hour < 10 ? '0' + hour : hour;
                var a = 'am';
            }
            return hour + ':' + (d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()) + ' ' + a;
        {% endif %}
    });

Do you have un idea on how implement the timezone gestion easily in JS by passing the string 'America/New_York' or 'Europe/Paris' in a second argument?

Thanx a lot!!

guillaumepotier
  • 7,369
  • 8
  • 45
  • 72

1 Answers1

0

First are you able to pass GMT dates to your JS instead of all these varying timezones? If so then what you can do is find the user's time zone in js.

var timeStamp = <?php echo strtotime($some_gmt_date_string); ?>  
//offset in minutes  
var offset = (new Date()).getTimezoneOffset();   
// timeStamp to milliseconds, offset to seconds to minutes  
var d = new Date(timeStamp*1000 - offset*60000);

Example:

//current time is 12:13
var timeStamp = 1333480422; //now in gmt time   
var offset = (new Date()).getTimezoneOffset(); //420, pacific time  
var d = new Date(timeStamp*1000 - offset*60000);  
return d; //Tue Apr 03 2012 05:13:42 GMT-0700 (Pacific Daylight Time) 
Parris
  • 17,833
  • 17
  • 90
  • 133
  • might not be the best way to go about this... essentially you need timeStamp to be some gmt time stamp – Parris Apr 03 '12 at 19:34