Sunday, September 15, 2024

A Roundup of Popular JavaScript Date Parsing Libraries: Datejs

A Roundup of Popular JavaScript Date Parsing Libraries: Datejs

Welcome to the second installment in a series on Date Parsing JavaScript libraries. The idea to look for libraries specializing in dates came to me while writing an article on Date Parsing using JavaScript and Regular Expressions. I was delighted to find that there were a lot of them out there. Having said that, not all are equally well suited for my particular need, which is to parse dates from a block of text. In part one, I talked about the outstanding Moment.js library. Part 2 focuses on the equally popular Datejs.

A Colorful History

The original Datejs release, named Alpha-1, was uploaded to the code.google.com repository in 2007 by Geoffrey McGill. Shortly thereafter, the project was abandoned, despite there being no mention of that on the site. Although the library showed great promise, the 120 plus reported bugs were left unaddressed, that is until Gregory Wild-Smith created his own project fork on GitHub named DateJS: Evolved (which I’ll simply refer to as Datejs for the rest of the article) and fixed many of the outstanding issues. By all accounts, this codeline is still active and can be considered stable.

A 2 Second Overview

There doesn’t seem to be whole lot of documentation on the GitHub site, so you might want to refer to the original project docs. All of that still applies, except that the new version adds internationalization via node.js as well as new tests, courtesy of Jasmine.

In addition to parsing, Datejs also validates date parts, formats date strings, and calculates the difference between two dates. Thanks to its “Syntactic Sugar”, it can accept English phrases such as “next friday” and “last April”:


// Convert text into Date Date.parse(‘today’); Date.parse(‘t + 5 d’); // today + 5 days Date.parse(‘next thursday’); Date.today().add(1).days(); // Is today Friday? Date.today().is().friday();

But Can It Parse?

What initially drew me in was the maker’s catch phrase that “Datejs doesn’t just parse strings, it slices them cleanly in two.” Sounds like just the kind of parsing power I need!

In truth, it’s not exactly what I was looking for. Although Datejs certainly can parse a date string with ease, it won’t extract the date and time from a larger string. Not to be deterred, I delved into the code to see if there was a regex in there that I could tweak. I don’t advise mucking about with library code that isn’t yours, but this is for my own personal use and not a production scenario.

Sure enough, I found a huge regex in the $P.ISO object, and, as luck would have it, the string start (^) and end ($) anchors are there. Hence, the date string must contain only the date and time element and nothing else.

$P.ISO = {
regex : /^([+-]?d{4}(?!d{2}b))((-?)((0[1-9]|1[0-2])(3([12]d|0[1-9]|3[01]))?|W([0-4]d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]d|[12]d{2}|3([0-5]d|6[1-6])))([Ts]((([01]d|2[0-4])((:?)[0-5]d)?|24:?00)([.,]d+(?!:))?)?(17[0-5]d([.,]d+)?)?s?([zZ]|([+-])([01]d|2[0-3]):?([0-5]d)?)?)?)?$/

I removed the position anchors and tried again, but alas, no dice. It only matched the year, resulting in a date of Sun Jan 01 2012 00:00:00 GMT-0500 (Eastern Standard Time) against my test string of “You have a doctor’s appointment on 2012/03/13 16:00. Please show up on time.”

.

That was enough to convince me that I would have to bring in my own parser to remove the date from the containing string. I just reused my simple regex:

var stringToParse = "You have a doctor's appointment on 2012/03/13 16:00.  Please show up on time.";
var dateString    = stringToParse.match(/d{4}/d{2}/d{2}s+d{2}:d{2}/);
var dt            = Date.parse(dateString[0]);
console.log(dt);  //prints Tue Mar 13 2012 17:00:00 GMT-0400 (Eastern Daylight Time) 

Using the parseExact() Method

Datejs also has a static parseExact() method that accepts a second argument that defines the expected date format. If you find that parse() chokes on your date format, you can always supply it to parseExact() to help Datejs along. Here is what my format above would look like:

var dt = Date.parseExact(dateString[0], "yyyy/MM/dd HH:mm");

Notice the use of the capital H for 24 hours. The docs are a little lacking in the time format department, but it looks like it uses the standard Unicode Locale Data Markup Language (LDML) to denote the various date parts.

Conclusion

While not quite as versatile as Moment.js, there is still a lot to recommend Datejs. Once you’ve got the date removed from the text block, you can safely let Datejs take things from there. Next month, we’re going to look at a library that lets you extend it for just the type of thing that we did here today. I personally like the idea of being able to append your own code to the library that it’s supporting.

Rob Gravelle
Rob Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured