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.

   1: function fnNow() {
   2:     var now = new Date();
   3:     alert(now);
   4: }
Thu Aug 6 22:49:52 EDT 2009 
Thu Aug 06 2009 19:43:34 GMT-0400 (Eastern Daylight Time)

UTC (Coordinated Universal Time) String

This example gets the date and time in a slightly different string format.

   1: function fnUTCString() {
   2:     var now = new Date();
   3:     alert(now.toUTCString());
   4: }
Thu, 6 Aug 2009 22:49:52 UTC 
Thu, 06 Aug 2009 23:44:14 GMT

UTC (Coordinated Universal Time) Number

The UTC() method takes a date and returns the number of milliseconds since midnight of January 1, 1970 according to universal time. 10 to 13 digits, last 3 digits for miliseconds.

Syntax: Date.UTC(year,month,day,hours,minutes,seconds,ms)

   1: function fnUTC() {
   2:     var now = new Date();
   3:     var d = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());
   4:     alert(d);
   5: }

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.

   1: function fnUTC2Date() {
   2:     var now = new Date();
   3:     var d = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());
   4:     // obtain local UTC offset and convert to msec
   5:     localOffset = now.getTimezoneOffset() * 60000;
   6:     var c = new Date(d + localOffset);
   7:     alert(c.toLocaleString());
   8: }

JavaScript Date To ISO8601

Since the toISOString() method is not available for Internet Explorer yet you will need to reformat a date into the ISO 8601 format yourself. The following code is just one way to accomplish this:

   1: function padzero(n) {
   2:     return n < 10 ? '0' + n : n;
   3: }
   4: function pad2zeros(n) {
   5:     if (n < 100) {
   6:         n = '0' + n;
   7:     }
   8:     if (n < 10) {
   9:         n = '0' + n;
  10:     }
  11:     return n;
  12: }
  13: function toISOString(d) {
  14:     return d.getUTCFullYear() + '-' +  padzero(d.getUTCMonth() + 1) + '-' + padzero(d.getUTCDate()) + 'T' + padzero(d.getUTCHours()) + ':' +  padzero(d.getUTCMinutes()) + ':' + padzero(d.getUTCSeconds()) + '.' + pad2zeros(d.getUTCMilliseconds()) + 'Z';
  15: }
  16: function fnToISO() {
  17:     var now = new Date();
  18:     alert(toISOString(now));
  19: }
This entry was posted in General, JavaScript, Programming and tagged , , , . Bookmark the permalink.

12 Responses to 6 Ways To Work With Dates In JavaScript

  1. Pingback: Linkeries #120809 - taggle.org

  2. Pingback: Weekly Link Post 106 « Rhonda Tipton’s WebLog

  3. Pingback: ContinousLearner: Links (8/13/2009) | Astha

  4. Pingback: Twitted by ricky709

  5. Pingback: JSON Date parameter passed to MVC Action is always null | Easy jQuery | Free Popular Tips Tricks Plugins API Javascript and Themes

Leave a Reply

Your email address will not be published.