1

I want to write a function that can convert the given timestamp as per given timezone codes. For Example:

getTimeStampforZone(new Date(), 'PST') //gives timestamp in pacific
getTimeStampforZone(new Date(), 'EST') //gives timestamp in eastern
getTimeStampforZone(new Date(), 'CT') //gives timestamp in China time zone

I am able to do it for few time zones but looks lke there is no support in Safari for "All" timezones.

I don't want to use any library.

Here is my code:

function getZoneTime(date, timeZone) {
    var options = {
        timeZone: timeZone,
        hour12: false,
        hour: '2-digit',
        minute: '2-digit'
    };
    var date = new Date(date);

    var localizedDate = new Date(date.toLocaleDateString('en-US', options));
    var localizedTime = date.toLocaleTimeString('en-US', options);

    return localizedDate.toString('yyyy-MM-dd') +' '+ localizedTime;
}
Bugs
  • 4,491
  • 9
  • 32
  • 41
JVM
  • 946
  • 1
  • 10
  • 23
  • `gives timestamp in eastern` eastern what? very UScentric assumptions on your part - odd, given you include Gina time zone – Jaromanda X Jun 19 '17 at 06:45
  • 1
    `I don't want to use any library.` - so, you'll end up writing something like [this library](http://momentjs.com/timezone/) if you want to do it correctly – Jaromanda X Jun 19 '17 at 06:46
  • My application presents timestamp of records in logged in user's timezone which can be different from the machine's timezone that is why I need conversion. – JVM Jun 19 '17 at 06:47
  • For simplicity, I am not caring about format. – JVM Jun 19 '17 at 06:49
  • What I actually need is list of timezone offsets if nothing else is required. – JVM Jun 19 '17 at 06:49
  • 1
    There is no standardisation for timezone names or abbreviations and some in common use are duplicated (e.g. EST). If you want to map abbreviations to offsets, you'll need to write your own mapping knowing that sometimes you'll get it wrong. Oh, and the ECMAscript Date object does not support timezones at all, it depends on the host system for the offset. – RobG Jun 19 '17 at 09:29
  • @JVM - You have not researched this problem thoroughly. Time zone abbreviations are not unique, nor do time zones map cleanly to a single offset. Please read [the timezone tag wiki](https://stackoverflow.com/tags/timezone/info). Also you have not defined your expected output, nor have you shown any effort to solve the problem yourself. StackOverflow is not a place to just give requirements and expect code written for you. Please show your efforts. I'm closing this as a duplicate, because the dup is close enough to your question, and the answer shows several possible approaches. – Matt Johnson-Pint Jun 19 '17 at 16:10

0 Answers0