Timezone specific / local string to local Date object in JavaScript

I was facing a frustrating problem today with JavaScript Date object creation. The api I was using was giving me a dateTimeString and if I create an instance of the JavaScript Date class with it, it was considering the string according to my local timezone. Below is the example of the problem.


Solution for this

Let’s first fix the problem mentioned above.

Let me tell you what I did exactly. I first create a date object from the given string. As my browser considered this as GMT, it first converted it accordingly in the command var date = new Date(datetimeStr);

But I know this time has a difference of GMT – myTimeZone. So I modified the minutes with the timeZoneOffset. This will push the time with the deviation it has with GMT. Thus problem solved.

Converting one timezone to another

Similar approach can be taken when you want to alter time not between GMT and local, but between a specific timezone to your own timezone. However this approach will only change the value, not the actual timezone in the date object.

Below is the example.

About This Author

Hello! I am Paul Shan, a JavaScript Expert, Full Stack and DevOps Engineer cum Consultant based out of Bengaluru, India.

  • Manish

    Two issues:

    1. This timezone conversion doesn’t work on IE (IE11) at all.. IE doesn’t accept timeZone as a parameter to ‘toLocaleString’.

    2. Even in chrome, DST is not being handled this way properly.

    For example, if I want to convert my current time to ‘Australia/Sydney’, I pass ukDate to date object in place of datetimeStr.
    It returns 3pm instead of 2am.

    But if I convert it to ‘Eurpoe/London’, result is correct.

    Similarly it works fine for ‘Pacific/Samoa’ but not for ‘Pacific/Gambier’.

    Let me know if you have/find any solution for these two issues..