« - »

ISO 8601 Date Formatting, Client-side

23 February 2008

I went searching through the Internet looking for a script to convert my new ISO 8601 dates back into something a little nicer to look at, and I found almost exactly what I was looking for on John Resig‘s site: JavaScript Pretty Date. The only little snag was that John’s dates were all UTC dates and mine had a time zone offset. I needed to account for the possible time zone differences between the server and the client, and I noticed in the comments section that Dean Landolt had taken the original code and reworked it with that in mind. Over on his site I found Humane dates with unobtrusive javascript, and so I downloaded humane.js. Unfortunately, this one also assumed UTC dates to start with, so I still had an issue. Still, I liked his changes, so I decided to start with his version.

To accommodate my particular needs, I replaced the first three lines of his version with one of my own:

//  var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," ");
//  var dt = new Date;
//  var seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() *
         60000)) / 1000);
    var seconds = (new Date() - convertISOStringToDate(date_str)) / 1000;

Then I added a small function down at the bottom to handle the possible difference between the offset on the server and the offset on the client:

function convertISOStringToDate(dateString) {
  var returnDate = null;

  var datePortion = dateString;
  var relativeOffset = 0;
  if (dateString.length > 19) {
    datePortion = dateString.substring(0,19);
    var timeZonePortion = dateString.substring(19);
    var sign = timeZonePortion.substring(0,1);
    if (sign == '+' || sign == '-') {
      var multiplier = -1;
      if (sign == '-') {
        multiplier = 1;
      }
      var localOffset = (new Date()).getTimezoneOffset();
      relativeOffset = (((timeZonePortion.substring(1,3) * 60) +
           (timeZonePortion.substring(4,6) * 1)) * multiplier) -
           localOffset;
    }
  }
  datePortion = datePortion.replace(/T/g, ' ');
  datePortion = datePortion.replace(/-/g, '/');
  returnDate = new Date(datePortion);
  if (relativeOffset != 0) {
    returnDate = new Date(returnDate.getTime() + (relativeOffset * 60000));
  }

  return returnDate;
}

Once that was done, it was just a matter of going through all of the current scripts and invoking this routine to format the dates. Things look much better, and the best part is, I didn’t have to do most of the work. Thanks, guys!


http://blog.restafarian.org/2008/02/iso-8601-date-formatting-client-side/

Comments are closed.

Sorry, the comment form is closed at this time.