6 Ways To Work With Dates In JavaScript

Yesterday I added another AJAX demonstration to my web site using the Reddit API. http://www.williamsportwebdeveloper.com/reddit.html The reddit API provides dates in the UTC number format which forced me to spend some time figuring out how to convert it into other date formats. Since I frequently deal with different date formats in JavaScript I decided to do some research on the topic and add a cheatsheet to my notes. I might as well share it with you because I don’t share this kind of knowledge often enough.

Get Current Date/Time

The first example just shows you how to get the current date and time. Note that this can vary slightly depending upon the browser. Also, it does not factor in your time zone.

The example above converts a UTC date in the numerical format, 1249585988774, into the string format. This is what I needed to work with the Reddit API.

1249585988774

ISO 8601

ISO 8601. Note that the "T" appears literally in the string, to indicate the beginning of the time element. Times are expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z"). Used in ATOM RSS feeds.

1:function fnISO() {

2:// Only works in Firefox using ECMAScript 5

3:var now = new Date().toISOString();

4: alert(now);

5: }

As noted in the code comment above, ECMAScript 5 will support the toISOString() method. Firefox 3.5 appears to be the only browser with a JavaScript engine that has this method for the Date object. This will make it easier to convert dates into the proper format for RSS feeds.

2009-08-06T23:36:31.390Z

UTC Number To JavaScript Date

In the following sample code, I finally factor in my time zone and convert an UTC date in the numerical format into a regular JavaScript Date object.