Date interval in javascript

How to Calculate the Difference between Two Dates in JavaScript

As mentioned in the Date Creation in JavaScript article, there are very few native date calculation functions in JavaScript. In fact, there are none other than to convert between local and UTC time. Left to their own devices, web developers have devised many ways of calculating date intervals, some of which are ingenious, while others are flawed or just plain wrong.

I’ve scoured the Internet for some of the very best date interval calculation formulas so that I may present them to you today in easy-to-use static Date functions. I hope you find them useful!

Adding and Subtracting from a Given Date

According to the documentation, Date setters expect an interval-appropriate value. The setDays() setter, for instance, expects a day from 1 to 31. But really, these ranges are nothing more than helpful recommendations because day values that lie outside of this range are rolled over/back into the next/preceding month(s). For example, attempting to assign a day of 30 to February causes the date to roll over into March:

var febDate = new Date(2010, 1, 14); //Month is 0-11 in JavaScript febDate.setDate(30); console.log(febDate.toDateString()); //displays Tue Mar 2 2010

The same roll over behavior occurs in all the other setters and even accounts for leap years:

var y2k = new Date(2000, 0, 1); y2k.setMonth(14); console.log('14 months after the new millenium is: ' + y2k.toDateString()); //displays Thu Mar 31 2001 var y2k = new Date(2000, 0, 1); y2k.setHours(-22); console.log('22 hours before the new millenium is: ' + y2k); //displays Fri Dec 31 1999 02:00:00 GMT-0500 (Eastern Standard Time)

The roll over behavior presents us with the means to easily apply date intervals by supplying them directly to the appropriate setter:

var y2k = new Date(2000, 0, 1); y2k.setDate(y2k.getDate() + 88); console.log('88 days after the new millenium is: ' + y2k.toDateString()); //displays Wed Mar 29 2000

Calculating the Difference between Two Known Dates

Unfortunately, calculating a date interval such as days, weeks, or months between two known dates is not as easy because you can’t just add Date objects together. In order to use a Date object in any sort of calculation, we must first retrieve the Date’s internal millisecond value, which is stored as a large integer. The function to do that is Date.getTime(). Once both Dates have been converted, subtracting the later one from the earlier one returns the difference in milliseconds. The desired interval can then be determined by dividing that number by the corresponding number of milliseconds. For instance, to obtain the number of days for a given number of milliseconds, we would divide by 86,400,000, the number of milliseconds in a day (1000 x 60 seconds x 60 minutes x 24 hours):

Date.daysBetween = function( date1, date2 ) < //Get 1 day in milliseconds var one_day=1000*60*60*24; // Convert both dates to milliseconds var date1_ms = date1.getTime(); var date2_ms = date2.getTime(); // Calculate the difference in milliseconds var difference_ms = date2_ms - date1_ms; // Convert back to days and return return Math.round(difference_ms/one_day); >//Set the two dates var y2k = new Date(2000, 0, 1); var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate()); var today= new Date(); //displays 726 console.log( 'Days since ' + Jan1st2010.toLocaleDateString() + ': ' + Date.daysBetween(Jan1st2010, today));

The rounding is optional, depending on whether you want partial days or not.

Читайте также:  Data types in java bytes

Converting Milliseconds to other Intervals

As long as you can calculate the number of milliseconds in an interval, you can come up with a number by dividing the total number of milliseconds by the number of milliseconds in the desired interval. What’s more, we can apply the modulus (%) operator to strip out that value to determine the next larger interval. The key is to always go from the smallest interval – milliseconds – to the largest – days:

Date.daysBetween = function( date1, date2 ) < //Get 1 day in milliseconds var one_day=1000*60*60*24; // Convert both dates to milliseconds var date1_ms = date1.getTime(); var date2_ms = date2.getTime(); // Calculate the difference in milliseconds var difference_ms = date2_ms - date1_ms; //take out milliseconds difference_ms = difference_ms/1000; var seconds = Math.floor(difference_ms % 60); difference_ms = difference_ms/60; var minutes = Math.floor(difference_ms % 60); difference_ms = difference_ms/60; var hours = Math.floor(difference_ms % 24); var days = Math.floor(difference_ms/24); return days + ' days, ' + hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds'; >//Set the two dates var y2k = new Date(2000, 0, 1); var Jan1st2010 = new Date(y2k.getYear() + 10, y2k.getMonth(), y2k.getDate()); var today= new Date(); //displays "Days from Wed Jan 01 0110 00:00:00 GMT-0500 (Eastern Standard Time) to Tue Dec 27 2011 12:14:02 GMT-0500 (Eastern Standard Time): 694686 days, 12 hours, 14 minutes, and 2 seconds" console.log('Days from ' + Jan1st2010 + ' to ' + today + ': ' + Date.daysBetween(Jan1st2010, today));

A Simple dateDiff() Function

There is no reason to write a function for each date/time interval; one function can contain all of the required intervals and return the correct value for the one we want. In the following function, the datepart argument tells it what interval we are after, where ‘w’ is a week, ‘d’ a day, ‘h’ hours, ‘n’ for minutes, and ‘s’ for seconds:

// datepart: 'y', 'm', 'w', 'd', 'h', 'n', 's' Date.dateDiff = function(datepart, fromdate, todate) < datepart = datepart.toLowerCase(); var diff = todate - fromdate; var divideBy = < w:604800000, d:86400000, h:3600000, n:60000, s:1000 >; return Math.floor( diff/divideBy[datepart]); > //Set the two dates var y2k = new Date(2000, 0, 1); var today= new Date(); console.log('Weeks since the new millenium: ' + Date.dateDiff('w', y2k, today)); //displays 625

A More Complete DateDiff() Function

Perhaps the above function looks like the Visual Basic function of the same name. In fact it is loosely based on it. I was planning on recreating it in its complete form for your enjoyment, but, thankfully someone has already beat me to it. That someone is Rob Eberhardt of Slingshot Solutions. It’s part of his excellent jsDate script. It’s free to use as long as you give credit where credit is due.

His function offers a lot of advantages over the simple one presented above. For starters, his can calculate the month interval, which cannot be done by dividing into the number of milliseconds since month lengths differ. It also supports setting the first day of the week to something other than Sunday. Finally, it adjusts for Daylight Savings Time, which affects intervals of a day (“d”) and larger:

Date.DateDiff = function(p_Interval, p_Date1, p_Date2, p_FirstDayOfWeek)< p_FirstDayOfWeek = (isNaN(p_FirstDayOfWeek) || p_FirstDayOfWeek==0) ? vbSunday : parseInt(p_FirstDayOfWeek); var dt1 = Date.CDate(p_Date1); var dt2 = Date.CDate(p_Date2); //correct Daylight Savings Ttime (DST)-affected intervals ("d" & bigger) if("h,n,s,ms".indexOf(p_Interval.toLowerCase())==-1)< if(p_Date1.toString().indexOf(":") ==-1)< dt1.setUTCHours(0,0,0,0) >; // no time, assume 12am if(p_Date2.toString().indexOf(":") ==-1)< dt2.setUTCHours(0,0,0,0) >; // no time, assume 12am > // get ms between UTC dates and make into "difference" date var iDiffMS = dt2.valueOf() - dt1.valueOf(); var dtDiff = new Date(iDiffMS); // calc various diffs var nYears = dt2.getUTCFullYear() - dt1.getUTCFullYear(); var nMonths = dt2.getUTCMonth() - dt1.getUTCMonth() + (nYears!=0 ? nYears*12 : 0); var nQuarters = parseInt(nMonths / 3); var nMilliseconds = iDiffMS; var nSeconds = parseInt(iDiffMS / 1000); var nMinutes = parseInt(nSeconds / 60); var nHours = parseInt(nMinutes / 60); var nDays = parseInt(nHours / 24); //now fixed for DST switch days var nWeeks = parseInt(nDays / 7); if(p_Interval.toLowerCase()=='ww') < // set dates to 1st & last FirstDayOfWeek var offset = Date.DatePart("w", dt1, p_FirstDayOfWeek)-1; if(offset)< dt1.setDate(dt1.getDate() +7 -offset); >var offset = Date.DatePart("w", dt2, p_FirstDayOfWeek)-1; if(offset) < dt2.setDate(dt2.getDate() -offset); >// recurse to "w" with adjusted dates var nCalWeeks = Date.DateDiff("w", dt1, dt2) + 1; > // return difference switch(p_Interval.toLowerCase()) < case "yyyy": return nYears; case "q": return nQuarters; case "m": return nMonths; case "y": // day of year case "d": return nDays; case "w": return nWeeks; case "ww":return nCalWeeks; // week of year case "h": return nHours; case "n": return nMinutes; case "s": return nSeconds; case "ms":return nMilliseconds; default : return "invalid interval: '" + p_Interval + "'"; >> var y2k = new Date(2000, 0, 1) //Month is 0-11 in JavaScript! var today= new Date(); console.log('Months since the new millenium: ' + Date.DateDiff('m', y2k, today)); //displays 143

Conclusion

All of these date calculations have been leading up to the final leg of this short series where we’ll be creating a form to calculate annualized returns of capital gains and losses. It will feature the new HTML5 Date Input control, as well as a jQuery widget fallback. But first, we will be creating some specialized functions to deal with leap years.

About the Author

Rob Gravelle resides in Ottawa, Canada, and is the founder of GravelleConsulting.com. Rob has built systems for Intelligence-related organizations such as Canada Border Services, CSIS as well as for numerous commercial businesses. Email Rob to receive a free estimate on your software project. Should you hire Rob and his firm, you’ll receive 15% off for mentioning that you heard about it here!

Источник

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; ireturn 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.

Источник

Оцените статью