DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 10.7 Parsing a Date from a String

10.7.1 Problem

You want to create a Date object from a string.

10.7.2 Solution

Create a custom parseDate( ) method that parses the individual date components (year, month, etc.) from the string using regular expressions and then assembles a new date.

10.7.3 Discussion

ActionScript does not provide any native methods for parsing a string into a Date object. This limitation does not necessarily pose a problem. For example, Flash Remoting allows you to return native Date objects from other applications. Even if you are not working with Flash Remoting, you can pass values between Flash and other applications using Epoch seconds/milliseconds. However, if you need to parse a string into a date, you should use a custom parseDate( ) method. This method takes the string value as a parameter, parses out each of the date's parts (the year, hour, etc.), and then returns a new Date object. Add the following code to your Date.as file for easy inclusion in other projects. The following code uses the custom RegExp class. See Recipe 9.6.

// You must include the third-party RegExp.as file from Recipe 9.6. One way to ensure
// this is to add #include "RegExp.as" to the Date.as file in which you also add the
// parseDate(  ) method.
#include "RegExp.as"

// This method also relies on the Date.months array from Recipe 10.2.
Date.parseDate = function (dateStr) {

  // Create local variables to hold the year, month, date of month, hour, minute, and
  // second. Assume that there are no milliseconds in the date string.
  var year, month, monthDate, hour, minute, second;

  // Use a regular expression to test whether the string uses ActionScript's date
  // string format. Other languages and applications may use the same format. For
  // example: Thu Dec 5 06:36:03 GMT-0800 2002
  var re = new RegExp(
    "[a-zA-Z]{3} [a-zA-Z]{3} [0-9]{1,2} [0-9]{2}:[0-9]{2}:[0-9]{2} .* [0-9]{4}",
    "g");
  var match = re.exec(dateStr);

  // If the date string matches the pattern, parse the date from it and return a new
  // Date object with the extracted value.
  if (match != null) {

    // Split the match into an array of strings. Split it on the spaces so the
    // elements will be day, month, date of month, time, timezone, year.
    var dateAr = match[0].split(" ");

    // Set the month to the second element of the array. This is the abbreviated name
    // of the month, but we want the number of the month (from 0 to 11), so loop
    // through the Date.months array until you find the matching element, and set
    // month to that index.
    month = dateAr[1];
    for (var i = 0; i < Date.months.length; i++) {
      if (Date.months[i].indexOf(month) != -1) {
        month = i;
        break;
      }
    }

    // Convert the monthDate and year from the array from strings to numbers.
    monthDate = Number(dateAr[2]);
    year = Number(dateAr[dateAr.length - 1]);

    // Extract the hour, minute, and second from the time element of the array.
    var timeVals = dateAr[3].split(":");
    hour   = Number(timeVals[0]);
    minute = Number(timeVals[1]);
    second = Number(timeVals[2]);

    // If the array has six elements, there is a timezone offset included (some date
    // strings in this format omit the timezone offset).
    if (dateAr.length == 6) {
      var timezone = dateAr[4];

      // Multiply the offset (in hours) by 60 to get minutes.
      var offset = 60 * Number(timezone.substr(3, 5))/100;

      // Calculate the timezone difference between the client's computer and the
      // offset extracted from the date string.
      var offsetDiff = offset + new Date().getTimezoneOffset(  );

      // Add the timezone offset, in minutes. If the date string and the client
      // computer are in the same timezone, the difference is 0.
      minute += offsetDiff;
    }

    // Return the new date.
    return new Date(year, month, monthDate, hour, minute, second);
  }

  // If the date string didn't match the standard date string format, test whether it
  // includes either MM-dd-yy(yy) or MM/dd/yy(yy).
  re = new RegExp("[0-9]{2}(/|-)[0-9]{2}(/|-)[0-9]{2,}", "g");
  match = re.exec(dateStr);
  if (match != null) {
    // Get the month, date, and year from the match. First, use the forward slash as
    // the delimiter. If that returns an array of only one element, use the dash
    // delimiter instead.
    var mdy = match[0].split("/");
        if (mdy.length == 1) {
          mdy = match[0].split("-");
        }
  
    // Extract the month number and day-of-month values from the date string.
    month = Number(mdy[0]) - 1;
    monthDate = Number(mdy[1]);

    // If the year value is two characters, then we must add the century to it. 
    if (mdy[2].length == 2) {
      twoDigitYear = Number(mdy[2]);
      // Assumes that years less than 50 are in the 21st century
      year = (twoDigitYear < 50) ? twoDigitYear + 2000 : twoDigitYear + 1900;
    } else {
      // Extract the four-digit year
      year = mdy[2];
    }
  }

  // Check whether the string includes a time value of the form of h(h):mm(:ss).
  re = new RegExp("[0-9]{1,2}:[0-9]{2}(:[0-9]{2,})?", "g");
  match = re.exec(dateStr);
  if (match != null) {
    // If the length is 4, the time is given as h:mm. If so, then the length of the
    // first part of the time (hours) is only one character. Otherwise, it is two
    // characters in length.
    var firstLength = 2;
    if (match[0].length == 4) {
      firstLength = 1;
    }

    // Extract the hour and minute parts from the date string. If the length of the
    // match is greater than five, assume that it includes seconds.
    hour = Number(dateStr.substr(match.index, firstLength));
    minute = Number(dateStr.substr(match.index + firstLength + 1, 2));
    if (match[0].length > 5) {
      second = Number(dateStr.substr(match.index + firstLength + 4, 2));
    }
  }
 
  // Return the new date.
  return new Date(year, month, monthDate, hour, minute, second);
};

Here are a few examples that show how you can use the parseDate( ) method to create a new Date object from a string. As with many of the examples in this chapter, the actual output will vary depending on your time zone settings.

#include "Date.as"

// Displays: Sat Oct 9 00:00:00 GMT-0700 1982
trace(Date.parseDate("10/09/1982"));

// Displays: Fri Oct 13 03:55:00 GMT-0700 1978
trace(Date.parseDate("It was 3:55 on 10-13-78"));

// Displays: Tue Dec 3 06:36:02 GMT-0800 2002
trace(Date.parseDate("Fri Dec 2 14:36:02 GMT+0800 2002"));
    [ Team LiB ] Previous Section Next Section