Force Timezone in Javascript Date

So I was working on a project for which I needed to force the Eastern timezone while displaying dates. Though not relevant to the post, I thought I need to share a few words about the method I chose to accomplish the task. I discovered prototype object (not the framework) today. (You are welcome to skip this section and proceed to the implementation) Here is an excerpt from the excellent Mozilla Development Network pages:

All objects in JavaScript are descended from Object; all objects inherit methods and properties from Object.prototype, although they may be overridden (except an Object with a null prototype, i.e. Object.create(null)). For example, other constructors’ prototypes override the constructor property and provide their own toString methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

The items we are interested in are:

  • they may be overriden
  • changes are propogated to all objects

This is applicable to both user defined types and built-in types in javascript. This is awesome! I decided to use the Object.prototype object to extend the built-in Date type to add some sugar to my code while keeping it readable.

Notice the extension of the built-in Date by the addition of getStandardTimezoneOffset() and isDst() methods. Also notice how getEastern(datetime) is not an extension but just a straight up javascript function since it is a very specific use case and it makes no sense to make this function available to all instances of Date.

The code is pretty self explanatory but if you have questions drop me a note and I’ll do my best to answer them. Accomplishing this task and this post would not be complete without posting references to the articles that guided me through this process.

  1. How to ignore user’s time zone and force Date() use specific time zone
  2. Check if Daylight Saving Time is in effect, and if it is for how many hours
  3. Daylight Saving Time
  4. Time Zone Offset Calculation

Leave a Reply

Your email address will not be published. Required fields are marked *