Parsing an ISO datestamp

Share this article

The fifth article in the small-and-sweet functions series is a follow up to the previous article, which showed you a simple function for creating an ISO datestamp. The previous article noted that this format is not supported by some older browsers as input to the Date constructor. This article will show you a reciprocal function, that parses ISO datestamps to produce a Unix timestamp, which can even be understood by IE6! The code for timestamp() is shown below.

function timestamp(datestamp)
{
  var pattern = /^([\d]{4})\-([\d]{2})\-([\d]{2})T([\d]{2}):([\d]{2}):([\d]{2})(Z|(?:[+\-][\d]{2}[:]?[\d]{2}))$/;
  if(!pattern.test(datestamp)) 
  { 
    return null; 
  }
  
  var 
  components = [], 
  zoneoffset = 0;
  datestamp.replace(pattern, function(a,y,m,d,h,i,s,z)
  {
    for(var bits = [y,m,d,h,i,s], i = 0; i < 6; i ++)
    {
      components[i] = parseInt(bits[i], 10);
    }
    components[1]--;
    
    if(z !== 'Z')
    {
      zoneoffset = 
      (
        (
          (parseInt((z = z.replace(':', '')).substr(1,2), 10) * 3600) 
          + 
          (parseInt(z.substr(3,4), 10) * 60)
        ) 
        * 
        (z.charAt(0) == '-' ? 1000 : -1000)
      );
    }
  });
  
  return Date.UTC.apply(Date, components) + zoneoffset;
}

What the Function Does

The timestamp() function takes an ISO 8601 datestamp, such as "2012-12-06T04:19:27+00:00", and converts it to a Unix timestamp – the number of milliseconds since the UTC epoch, which in this example would be 1354767567000. The timestamp integer is exactly the same as that produced by the Date.getTime() method, and in most modern browsers we can get from one to the other like this:
new Date("2012-12-06T04:19:27+00:00").getTime();
However that’s not supported by some older browsers – most significantly IE8 or earlier, but also Safari 3. The timestamp() function fills that gap, by providing intermediate conversion that works in older browsers. Whenever you need to parse an ISO datestamp as a Date, you simply pass it through the timestamp() function first, as shown below.
new Date(timestamp("2012-12-06T04:19:27+00:00"));

How the Function Works

The timestamp()
function takes advantage of the static Date.UTC() method, which takes a set of numeric date components as its input, like this:
Date.UTC(2012, 11, 6, 4, 19, 27);
In essence, all we have to do is split the datestamp into those components, then pass them all to Date.UTC(), and we’ll get a Unix timestamp. However, it’s not quite as simple as that! To begin with, the datestamp is validated using a simple regular expression. It could have been more precise, but simpler expressions are cheaper to parse, and we can usually assume that the input format will either be exactly correct, or not an ISO datestamp at all. Nonetheless, if you do pass a datestamp with wildly inaccurate values, the browser will still handle them with aplomb. For example, if you specify a date of "2012-26-00" it wil be treated as the 31st of January, 2014 – adding a year and two months for the month "26", and then subtracting a day for the date "00". If the datestamp fails validation then the timestamp() function returns null. Otherwise, it proceeds to split the datestamp into its component integers. This is done using string replace with a callback, which is a powerful way of parsing strings. The callback function is passed a set of arguments that correspond with the regex matches – one for the overall match, and then one for each of the backreferences. Within the callback, we parse those values to integers, and save them to an array. For month values, we also have to reduce the value by one, because JavaScript month numbers range from 0 to 11, where our input is "01" to "12". Next, we parse the timezone-designator, which could be "Z"
for a UTC datestamp, or it could be an offset like "+10:00" or "-0600". The offset is converted to an integer in seconds, and then converted again to positive or negative milliseconds, depending on which way the offset goes. Finally, we pass the component integers to Date.UTC(), then add the timezone offset to the value that returns. The UTC() method assumes that its input components are already UTC format, so we have to add the timezone offset to compensate the value. apply() is used to call the UTC() method, because it allows the components array to be passed as a single argument.

Conclusion

The timestamp() and datestamp() functions are both invaluable additions to the JavaScripter’s toolkit, providing the ability to create and parse the ubiquitous ISO format. These functions prove to be useful, especially in those old and cranky browsers we’d rather forget!

Frequently Asked Questions (FAQs) about Parsing an ISO Datestamp

What is an ISO Datestamp and why is it important?

An ISO Datestamp is a standardized way of representing dates and times, as defined by the International Organization for Standardization (ISO). It is important because it ensures consistency and eliminates confusion in date and time representation across different systems and platforms. This is particularly crucial in programming and data management where accurate and consistent date-time data is essential.

How do I parse an ISO Datestamp in JavaScript?

Parsing an ISO Datestamp in JavaScript can be done using the built-in Date object. For example, if you have an ISO Datestamp string like “2022-03-01T12:00:00Z”, you can create a new Date object with it: let date = new Date("2022-03-01T12:00:00Z");. This will give you a Date object that you can manipulate using various Date methods.

What is the difference between a date and a datestamp?

A date refers to a specific day in the calendar, while a datestamp includes both the date and the time of an event. In other words, a datestamp is a more precise measure of a point in time, often used in computing and data management to track events or changes.

How can I use a datestamp in my web development project?

Datestamps can be used in a variety of ways in web development. They can be used to track user activity, log events, or manage content updates. For example, you might use a datestamp to record when a user last logged in, or when a piece of content was last updated.

What are some common issues when working with ISO Datestamps and how can I avoid them?

One common issue is time zone differences. The ISO Datestamp is in Coordinated Universal Time (UTC), so you’ll need to convert it to the user’s local time zone. JavaScript’s Date object can handle this conversion for you. Another issue is date format differences. Different countries use different date formats, so make sure to format the date in a way that’s appropriate for your audience.

Can I use datestamps in other programming languages?

Yes, most programming languages have built-in support for date and time manipulation, including parsing and formatting ISO Datestamps. The exact methods and syntax may vary between languages, so you’ll need to refer to the specific language’s documentation.

What are date stamps used for in physical documents?

In physical documents, date stamps are used to indicate when the document was received, sent, or processed. This can be important for record-keeping and tracking the progress of paperwork.

How can I create a custom datestamp format?

In JavaScript, you can use the toLocaleDateString and toLocaleTimeString methods of the Date object to create custom date and time formats. You can specify the locale and options to control the output format.

What is the difference between timestamp and datestamp?

A timestamp is a sequence of characters or encoded information identifying when a certain event occurred, usually giving date and time of day, sometimes accurate to a small fraction of a second. A datestamp, on the other hand, is a timestamp that, in addition to time of day, includes the date.

How can I convert a datestamp to a different time zone?

JavaScript’s Date object automatically converts datestamps to the user’s local time zone. If you need to convert to a different time zone, you can use libraries like Moment.js, which provide more advanced date and time manipulation features.

James EdwardsJames Edwards
View Author

James is a freelance web developer based in the UK, specialising in JavaScript application development and building accessible websites. With more than a decade's professional experience, he is a published author, a frequent blogger and speaker, and an outspoken advocate of standards-based development.

functionsIntermediate
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week