When working with Date types in JavaScript, we often have
the need to do date difference calculations. An approach to provide this
functionality would be to extend the Date type with functions that can handle
the calculations. So let’s talk about how to create these extension methods.
We can create extension methods on any JavaScript object by
using the Object.prototype property. This property allows us to associate
dynamic properties and functions to an object. This is what we use to associate
the following functions to any Date instance.
Extension
methods:
/*
Date
type Extension Methods
Source:
ozkary.blogspot.com
Date:
4/27/2014
*/
//Month
difference
Date.prototype.monthDiff
= function
(dtBefore) {
var yr = (this.getFullYear() - dt.getFullYear()) * 12;
var mn = ((this.getMonth() + 1) - (dt.getMonth() + 1));
return yr + mn;
}
//year
difference
Date.prototype.yearDiff
= function
(dtBefore) {
var yr = (this.getFullYear() - dt.getFullYear());
return yr;
}
//date
format
Date.prototype.toShortDate
= function
() {
var dt = (this.getMonth() + 1) + '/' + this.getDate() + '/' + this.getFullYear();
return dt;
}
Function
name
|
Description
|
monthDiff
(date)
|
This
extension method expects a date type as a parameter. It uses native functions
to calculate the years and months difference between itself (this) and the
date parameter.
|
yearDiff
(date)
|
This
extension method expects a date type as a parameter. It uses native functions
to calculate the year difference between itself (this) and the date parameter
|
toShortDate
|
This
extension method uses the native functions to extract the date parts (month,
day, year) and return the short date format (mm/dd/yyyy)
|
Usage:
Now that we have our new functions available, we can work on
showing a way to use them. We can do that by comparing a couple of date ranges to display
the difference in months and years. In our examples, we use the most recent
date as the extended object, and pass the before date as the parameter. This
allows us to get positive values for the date difference calculation.
var date1 = new Date('2/16/2014');
var date2 = new Date('09/01/2009');
$('#dates1').text(date1.toShortDate()
+ ' - ' +
date2.toShortDate());
//get
the date difference
var m = date1.monthDiff(date2);
var y = date1.yearDiff(date2);
$('#m1').text(m);
$('#y1').text(y);
//get
the date difference
date1
= new Date('3/28/2014');
date2
= new Date('12/28/1996');
$('#dates2').text(date1.toShortDate()
+ ' - ' +
date2.toShortDate());
m
= date1.monthDiff(date2);
y
= date1.yearDiff(date2);
$('#m2').text(m);
$('#y2').text(y);
This script performs the following steps:
- Create Date instances
- Display the short date format (mm/dd/yyyy)
- Calculate the months and year differences
The result should look as shows below. We can also use this
JSFiddle sample to see it in action.
Thanks for following and keep an eye for additional entries.
0 comments :
Post a Comment
What do you think?