Learn how to parse properly a date in Moment.js that has a 2 digits year.

How to parse a date with two (2) digits year using Moment.js

After years working with dates and JavaScript libraries that parse dates, today I found something that never happened to me before, basically because normally you will always obtain a date in its full format (Day/Month/Year ~ 31/12/1997 or Month/Day/Year ~ 12/31/1997), that's how it is usually, until this day, where I had to work with a dataset that was in JSON format and their dates were stored in the following format: MM/DD/YY (that's right, only the last 2 digits of the year).

I had to import this to the database, so of course, there were importing errors due to the format of the dates. The only thing left was to parse the JSON with JavaScript and generate a normal JSON file with the proper format. Thanks to Moment.js this is really simple to achieve with a code like the following one:

let moment = require('moment');

// The input date is November 15th 1968 (but in the 0/15/68 format)

// I would expect an output in the regular format with the following result: 1968-10-15
// However, if you run this code, you will get instead: 2068-10-15
console.log(moment("10/15/68", "MM/D/YY").format("YYYY-MM-DD"));

That's right! Converting the 10/15/68 date with the given format will parse the year wrong in this case, as someone that was born in 1968, shouldn't have the year 2068 on its birth date.

Hotfix

The real solution would be to obtain the dates in the full format as everyone should do YYYY-MM-DD. However, if you have no other option than parse the 2 digit years, then the following fix will help you out. According to the Moment.js documentation:

By default, two digit years above 68 are assumed to be in the 1900's and years 68 or below are assumed to be in the 2000's. This can be changed by replacing the moment.parseTwoDigitYear method. The only argument of this method is a string containing the two years input by the user, and should return the year as an integer.

This basically translates that you should implement some custom code to handle this situation:

let moment = require('moment');

moment.parseTwoDigitYear = function (yearStr) {
    return parseInt(yearStr) + (parseInt(yearStr) > 19 ? 1900 : 2000);
};

// This will print: 1968-10-15
console.log(moment("10/15/68", "MM/D/YY").format("YYYY-MM-DD"));

// This will print: 2001-10-15
console.log(moment("10/15/01", "MM/D/YY").format("YYYY-MM-DD"));

This should do the trick in most of the cases, if you're out of luck and this doesn't cover your case, you may customize the code and adjust it if you have some extra data like the age of the person or something like that.

Happy coding ❤️!


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors