1

I have a function for converting a date from server timezone to client/user timezone. It's based on Displaying date/time in user's timezone - on client side:

function getLocalDate(sourceDate){

    if(sourceDate === '' || sourceDate === null){
        return "";
    }

    var d = new Date(sourceDate);

    var  hours    = d.getHours(),
        min       = d.getMinutes() + '',
        pm        = false,
        months    = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

    if(hours > 11){
        hours = hours - 12;
        pm = true;
    }

    if(hours == 0) hours = 12;
    if(min.length == 1) min = '0' + min;

    dStr = months[d.getMonth()] + ' ' + d.getDate() + ' '  + d.getFullYear() + ', ' + hours + ':' + min + ' ' + (pm ? 'PM' : 'AM');

    return dStr;
}

The function gets a date/time with timezone (set from server) and outputs same date/time but in browser timezone.

The conversion works perfectly for US timezones (EST, CST, etc). For other timezones - e.g. CEST (Germany), EAT (Kenya), IST (India) - I am getting mixed results. Sometimes I get undefined NaN NaN, NaN:NaN AM. Othertimes I get a proper date/time but far off from true i.e. conversion gives a time that's ahead or behind.

Can browser date/time conversion work for non-US timezones?

Thanks.

Community
  • 1
  • 1
Mugoma J. Okomba
  • 3,185
  • 1
  • 26
  • 37
  • why do you check for `hours > 11` ? should not be `hours > 12`? 12 a.m it is valid, 0 a.m doesn't make sense, then instead of `(sourceDate === '' || sourceDate === null)` you can use `!sourceDate`, it will also check `undefined`, `0` and `false` – Francesco Oct 21 '15 at 07:02
  • Time zones are hard, and you cannot rely on abbreviations. Try [moment.js](http://momentjs.com) instead. (Use the moment-time zone add on.) – Matt Johnson-Pint Oct 21 '15 at 07:11

0 Answers0