Timezone specific / local string to local Date object in JavaScript

author-avatar
Paul Shan Tue Sep 22 2015
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.

Problem

var datetimeStr = "2015-10-13T12:30:00"; //I know that this time is not GMT but my own time zone
//as I am aware of the api
//But my browser JS engine doesn't

var date = new Date(datetimeStr);
console.log(date.toString()); //Tue Oct 13 2015 18:00:00 GMT+0530 (India Standard Time)

/*
as I am in India
my browser considered the string as GMT
and converted the time accordingly for IST
Because of this, the time which was 12:30pm
became 6pm
*/

Solution for this

Let’s first fix the problem mentioned above.
var datetimeStr = "2015-10-13T12:30:00";
var date = new Date(datetimeStr);
date.setMinutes(date.getMinutes()+date.getTimezoneOffset());
console.log(date.toString()); //Tue Oct 13 2015 12:30:00 GMT+0530 (India Standard Time)
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.
var datetimeStr = "2015-10-13T12:30:00"; //suppose this is UK time
/*
Now you want to make a date object
which holds this date time in ur time zone
*/
var ukDate = new Date(new Date().toLocaleString("en-UK",{timeZone:'Europe/London'})); //London current time 
var myDate = new Date(); //My current time

var timeDifference = myDate - ukDate;
var differenceInMinutes = Math.floor(timeDifference/(1000*60));

var date = new Date(datetimeStr);
date.setMinutes(date.getMinutes()+date.getTimezoneOffset()+differenceInMinutes);
console.log(date.toString()); //Tue Oct 13 2015 17:00:00 GMT+0530 (IST)

Javascript

Written By

Paul Shan

Collections

  • E

    ES6

  • R

    React JS

  • C

    CSS

    Cascading style sheets only

  • S

    SEO

    Search engine optimization

  • E

    ES7

  • C

    CMS

    wordpress, drupal, jumla, magento and more


Show All

Tags

vue-js
advanced js
youtube
Web development
vue css
social share buttons
real-life-example
react datetime picker
progra
Online
MathJax
jsfiddle
jquery chart library
instant search using vue
handlebars
event loop
Design
console.log
best practices
imorph

Show All