Tuesday, November 5, 2024

Formatting JavaScript Date Intervals into Years, Months, Weeks, and Days

Formatting JavaScript Date Intervals into Years, Months, Weeks, and Days

In my Calculating the Difference between Two Dates in JavaScript article, I presented a few ways of calculating the difference between two dates using some of JavaScript’s particular behaviors such as the roll over effect. I also described how to convert milliseconds into other intervals such as days, hours, and minutes. Since that article was posted, several readers have asked me how to express time intervals in terms of weeks, months, and years. Unfortunately, due to the variability of month lengths and leap years, calculating months and years is fraught with challenges. That being said, it can certainly be done. In fact, it already has.

Introducing the moment.js Library

My original intention was to look up some code snippets on the Internet as I did in the Calculating the Difference between Two Dates in JavaScript article. I managed to find a few, but while testing them, I found them to be either overly simplistic or unreliable. Luckily, my search also led me to the moment.js library, which was created specifically for parsing, validating, manipulating, and displaying dates in JavaScript. One area of functionality, on getting the difference between two dates, is of particular interest to us today.

Including the Script

You can download the script from the moment.js site, but I prefer to simply reference the hosted script at cloudflare.com. Just set the script tag’s src property to “//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js”.

The Moment Object

Before calling moment.js functions, you first have to wrap a “date” inside a moment() wrapper. I put the “date” inside quotation marks because the moment() wrapper actually accepts several object types that can represent a date, including:

  • another Moment object
  • a parsable String
  • a Date object
  • an Array of Date parts

Here are some examples of each:

var a = moment(new Date());
var b = moment('2000-01-01');
var c = moment(a);
var d = moment([2007, 0, 29]);

The diff() Function

To calculate a time interval between a moment object and another date, you would invoke the diff() function on the moment object and pass in the second date in any of the above formats. It returns the number of milliseconds. For example, to calculate the number of milliseconds that have elapsed since January 1st, 2000, you would wrap the later date (today) in the moment wrapper and then call diff(), passing a “date” object representing the Y2K milestone:

var today   = moment(new Date()),
    y2k     = new Date(2000, 0, 1);
   
console.log( today.diff(y2k) ); //outputs 533744070037

Returning other Time Intervals

To obtain the difference in another unit of measurement, you can pass the desired measurement as the second argument. The supported measurements are years, months, weeks, days, hours, minutes, and seconds. As of version 2.0.0, the singular forms are supported as well.

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

Month and Year Caveats

Be aware the the diff() function employs some special handling for month and year intervals. It operates under the assumption that two months with the same date should always be a whole number apart. Hence,

  • Jan 15 to Feb 15 should be exactly 1 month.
  • Feb 28 to Mar 28 should be exactly 1 month.
  • Feb 28 2011 to Feb 28 2012 should be exactly 1 year.

Outputting a Detailed Interval String

The diff() function makes it quite easy to output a detailed date interval by combining it with the moment add() function. If we add the interval to the start date before calculating the next (smaller) interval, we effectively isolate each interval type. When strung together, we get a detailed interval string, broken down by each type of our intervals array:

Date.getFormattedDateDiff = function(date1, date2) {
  var b = moment(date1),
      a = moment(date2),
      intervals = ['years','months','weeks','days'],
      out = [];

  for(var i=0; i<intervals.length; i++){
      var diff = a.diff(b, intervals[i]);
      b.add(diff, intervals[i]);
      out.push(diff + ' ' + intervals[i]);
  }
  return out.join(', ');
};

var today   = new Date(),
    newYear = new Date(today.getFullYear(), 0, 1),
    y2k     = new Date(2000, 0, 1);
 
  //(AS OF NOV 29, 2016)
  //Time since New Year: 0 years, 10 months, 4 weeks, 0 days
  console.log( 'Time since New Year: ' + Date.getFormattedDateDiff(newYear, today) );
 
  //Time since Y2K: 16 years, 10 months, 4 weeks, 0 days
  console.log( 'Time since Y2K: ' + Date.getFormattedDateDiff(y2k, today) );

The Demo

A demo is available on Codepen. Note that the HTML5 date type is not supported in Internet Explorer, Firefox, or Safari. However, that doesn’t prevent you from entering the dates. You just won’t get a calendar control.

Conclusion

Due to the variability of month lengths and leap years, calculating time intervals between two dates is not something that you should try to do yourself. Nor should you rely on user code that you come across in programming forums. Your best bet is a well-tested and proven library like moment.js.

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