Javascript: Adjusting time-zone differences
Jacob Hunsaker
Posted on March 24, 2021
Using DateTime in JS is sometimes very annoying. When we're trying to manipulate Date objects, many times, we end up with time-zone differences, maximum days differences in months, wrong format, etc. This post will be mainly talking about a handy function I keep for adjusting timezone differences.
Unless we're using other JS packages such as moment.js, we are stuck with the basic JS Datetime object. Here is the documentation. The documentation is very well-written with great examples to understand. What I would like to use from the documentation today is Date.prototype.getTimezoneOffset(). This built-in Datetime function returns the time-zone offset in minutes for the current location to UTC. For example, if you're in MST, the time-zone offset would be -7, since it is 7 hours behind UCT.
So, now let's get into the function.
adjustForTimezone(date) {
let timeOffsetInMS = date.getTimezoneOffset() * 60000;
date.setTime(date.getTime() - timeOffsetInMS);
return date
}
This function takes in a date parameter and changes the offset to Milliseconds. Date.setTime() gathers a millisecond value and outputs a Datetime value into the given parameter in the format (Day Mon dd yyyy hh:mm:ss Timezone).
Once we get the correct date, now we're up to changing the format to match the requirements package we're using needs or to simply make it more visually appealing.Β
For a sample page using this function, please check this simple Github repository using Vue.js.
If there are things I could improve on, please don't hesitate to let me know! I'm all ears :)
Posted on March 24, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.