Sleight of Date

3012015

Flickr: by Paolo Margari

Someone posted an interesting JavaScript question recently at StackOverflow, concerning how one may convert a date string into Unix time without the timezone effecting the result. In reflecting on that question, I also discovered a “trick” by which one can fool a local date object to a degree.

Consider the following snippet which converts Valentine’s Day midnight 2014 as a string to Unix time:

JavaScript’s Date Object, usually functions as a constructor for instantiating a new date object. In this case it does nothing of the sort; its presence permits the static UTC() method to execute. Alternately, you could use Date.parse() with date_str as a parameter to achieve the same outcome, a benefit of which is less code. However, Date.UTC() lends itself nicely to self-documenting the code; one knows that this static method clearly deals with UTC time.

One immediate question concerns its result, how do you really know that ms contains the correct value? There are two ways to check it, the easiest of which is as follows:

Passing date_str as a parameter to create a new date object in local time may seem odd until you realize that such objects among their many methods, come with a slew of UTC-oriented ones. When the UTCString method parses ms, it proves the credibility of its value.

The following snippet indicates a different way of getting Unix time, as follows:

The getTime method (like valueOf(), too) returns UTC time in milliseconds. When these are parsed, the result may be incorrect if you dutifully pass the Date constructor the numeric parameters it expects, in which case, instead of seeing a time of midnight, 8:00 a.m displays, owing to the PST timezone having an offset from UTC of minus eight hours.

One can trick the local date object if its argument is a numeric string conforming to the international standard of the month, day, and year format. Then, the local date object will be unaware as to what timezone that string pertains, so the timezone defaults to 0, i.e. UTC’s timezone. You still need to use the toUTCString method, to see a pure UTC result. Otherwise, if you simply use the toString method, the local date object will append information about the local timezone.

There is another way to check the value that ms contains. The solution requires far more code but, in exchange, it offers more flexibility in formatting the result, as follows:

This second example creates an interesting array of date parts as objects. Each one features a toString() method, which pads single digits with a zero and facilitates joining an object’s property value with others. After the UTC() method retrieves the precise time in milliseconds, the script passes that data to a local date object’s relevant methods. That object, a creation by “sleight of date”, i.e. using the aforementioned date string “trick”, provides a pure UTC result.