Extending The JavaScript Date Object with User Defined Methods

Extending The JavaScript Date Object with User Defined Methods

Got something to say?

Share your comments on this topic with other web professionals

In: Articles

By Lawrence O’Sullivan

Published on March 4, 2008

Applications, particularly business applications, can often require a lot of date manipulation, but that code could be simplified if JavaScript’s core Date object had some additional methods. In this article, I will show you how to add custom methods to the Date object that are inherited by each date instance.

Of course, all of the methods shown here could be written as global functions, but there are some advantages to this technique. By extending JavaScript’s Date object, the global namespace is less cluttered, the code is more readable, and performance is slightly better (albeit only by nanoseconds). It has all the benefits of object-oriented coding.

A demo of all the functions shown here is available if you want to see the code in action.

How it works

This technique takes advantage of how objects are implemented in JavaScript. Programmers may think of languages like C++ and Java when talking about object-oriented code. In those languages, a strictly-typed class defines each object—it’s all settled before runtime. JavaScript is prototype based. A constructor function defines the object and the methods can be extended at runtime. Inheritable methods and properties are assigned to the constructor function’s prototype property, which is itself an object. Methods and properties are created by assignment, and new or existing instances inherit them.

Date.prototype.method_name = function ([arguments]) {   // Code goes here }; 

Here, an anonymous function is assigned to a named property, method_name, of the prototype object. The syntax to call the method is:

date_instance.method_name([arguments]); 

Within the method’s code, the key word this refers to the object instance.

Now we know how it works, let’s make the built-in Date object a little more useful!

Copying Dates

In JavaScript, assignment of objects creates a reference to an object, NOT a copy of the object. In the following code, date1 is initialized to February 10, 2008 and assigned to date2. Since date2 is not a copy of date1, changing the day to the 20th affects date1 and both dates are February 20, 2008 in the alert box. They are, in fact, the same date instance.

var date1 = new Date(2008, 1, 10); var date2 = date1; date2.setDate(20); alert(date1 + "n" + date2); 

To copy a date, it needs to be converted to a primitive value (String, Number, or Boolean) and a new date created. The getTime() method is perfect for this. It returns the internal millisecond representation of the date and can be used as an argument for the date constructor. Here is the basic code:

var oldDate = new Date(); // today var dateCopy = new Date(oldDate.getTime()); 

Rather than write these lines everywhere they are needed, or create a global function, we’ll add an inheritable copy() method to the Date constructor:

Date.prototype.copy = function () {   return new Date(this.getTime()); }; 

And, here is an example of its use:

var oldDate = new Date(2008, 1, 10); var newDate = oldDate.copy();  newDate.setDate(20); alert(oldDate + "n" + newDate); 

Changing newDate does not affect oldDate. The dates shown in the alert are February 10, 2008 and February 20, 2008. This method is useful when you need to perform some date arithmetic and retain the original date.

Getting Date Information

Our next four methods are created to retrieve the name or abbreviation of the weekday or month of a date. Two arrays are created: one for day names, and the second for month names. The date object’s getDay() or getMonth() methods return an index used to access the value in the day names or month names array.

Beyond the issues with using global functions mentioned earlier, there is another risk. The arrays (all variables) are not constants and are vulnerable to being changed. Constants can be declared with the key word const in newer versions of JavaScript, but this is not supported by the majority of browsers in use. Fortunately, JavaScript offers alternatives.

The arrays can be made properties of the date constructor removing them from the global name space. There are two ways to do this: as static properties or inheritable properties. An example of a static property is PI, which is a static property of the Math object. The arrays are added to the Date constructor by assignment as shown below.

Date.DAYNAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", ...   "Friday", "Saturday"]; Date.MONTHNAMES = ["January", "February", "March", "April", "May", "June", "July", ...   "August", "September", "October", "November", "December"]; 

The arrays can then be accessed throughout your code like this:

Date.DAYNAMES[index]; 

A second option is to make the arrays properties of the date constructor’s prototype object:

Date.prototype.DAYNAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", ...   "Friday", "Saturday"]; Date.prototype.MONTHNAMES = ["January", "February", "March", "April", "May", "June", "July", ...   "August", "September", "October", "November", "December"]; 

The difference between these two approaches is that these are inherited and only accessible to Date methods using the key word this. (This approach is used thoughout the article.)

There is a third compromise—we can do both. For example:

Date.DAYNAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", ...   "Friday", "Saturday"]; Date.prototype.DAYNAMES = Date.DAYNAMES; 

(Having brought up the topic of static properties and methods, It should be mentioned that the methods as presented here cannot be static, but have to be assigned to the prototype object. Minor changes would be required to convert the methods to static methods.)

Going global? Here is your opportunity to internationalize your code. The DAYNAMES and MONTHNAMES code can be separated from the other methods so that language-specific day and month names can be set:

Date.prototype.DAYNAMES = ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", ...   "Vendredi", "Samedi"]; Date.prototype.MONTHNAMES = ["Janvier", "Fevrier", "Mars", "Avril", "Mai", ...   "Juin", "Juillet", "Aout", "Septembre", "Octobre", "Novembre", "Decembre"]; 

With the arrays in place, four methods can be defined with the following code:

Date.prototype.getFullDay = function() {   return this.DAYNAMES[this.getDay()]; }; Date.prototype.getDayAbbr = function() {   return this.getFullDay().slice(0, 3); };  Date.prototype.getFullMonth = function() {   return this.MONTHNAMES[this.getMonth()]; }; Date.prototype.getMonthAbbr = function() {   return this.getFullMonth().slice(0, 3); }; 

And here is an example using these methods.

var example_date = new Date(2008, 1, 20); alert("Day: " + example_date.getFullDay() +   "nDay abbr: " + example_date.getDayAbbr() +   "nMonth: " + example_date.getFullMonth() +   "nMonth Abbr: " + example_date.getMonthAbbr()); 

The alert box displays:

Day: Wednesday Day abbr: Wed Month: February Month: Abbr Feb 

Formatting the Time of Day

The Date object has two methods to retrieve a string representation of the time part of the date: toTimeString() and toLocaleTimeString(). The format of the string is based on client settings, and can vary from user to user. While this is generally good, it may not work in your application. The following two methods return a defined format.

The first returns the time in “hh:mm:ss am/pm” format with the numbers padded to two digits.

Date.prototype.to12HourTimeString = function () { var h = thi  s.getHours();   var m = "0" + this.getMinutes();   var s = "0" + this.getSeconds();    var ap = "am";    if (h >= 12) {     ap = "pm";      if (h >= 13)       h -= 12;   } else if (h == 0)     h = 12;   }    h = "0" + h;   return h.slice(-2) + ":" +     m.slice(-2) + ":" +     s.slice(-2) + " " + ap; }; 

The second method returns the time in 24-hour format, again padding the numbers to two digits.

Date.prototype.to24HourTimeString = function () {   var h = "0" + this.getHours();   var m = "0" + this.getMinutes();   var s = "0" + this.getSeconds();   return h.slice(-2) + ":" + m.slice(-2) + ":" + s.slice(-2); }; 

Perhaps the only interesting code is the use of slice(). To pad the numbers, they are concatenated with a leading zero, and then slice() is used to grab the rightmost 2 digits. If the number is less than 10, the extra leading zero is included. The methods would be used like this:

var dte = new Date(2008, 1, 20, 19, 30, 5); alert(dte.to12HourTimeString() + "n" + dte.to24HourTimeString()); 

The alert box displays:

07:30:05 pm 19:30:05 

Get the Number of Days in the Month

Sometimes it is necessary to know how many days are in a month. While an array can be used for this with some extra code for February, there is a simpler way to do it.

JavaScript will overflow (or underflow) dates created with otherwise invalid values. For example, if we create the date February 33, 2008 as:

var d = new Date(2008, 1, 33); alert(d); 

The date created and displayed in the alert is March 4, 2008 (2008 is a leap year).

Consequently, we can say the last day of a month—and number of days in the month—is the zero day of the following month—one day before the 1st. The following month is calculated as the current month (date.getMonth()) plus one. JavaScript will return January of the next year when one is added to December so this crosses years as well as months. The code to calculate the last day of a month is:

Date.prototype.lastday = function() {   var d = new Date(this.getFullYear(), this.getMonth() + 1, 0);   return d.getDate(); }; 

The number of days in the month of any date is found like this:

var d = new Date(2008, 1, 5); alert(d.lastday()); 

The alert box will show the number of days in the month: in this example, 29. (The second argument, 1, in the date constructor is February: January is 0.)

Find the Number of Days Between Two Dates

Business projects frequently need to determine the number of days between two dates. We’ll create a getDaysBetween() method—but first, let’s add another property to the date constructor’s prototype called msPERDAY. Its value is the number of milliseconds in 24 hours. This line of code is all we need.

Date.prototype.msPERDAY = 1000 ∗ 60 ∗ 60 ∗ 24; 

Or, in English: 1000 milliseconds in a second, 60 seconds in a minute, 60 minutes in an hour, 24 hours in a day.

In most cases, determining the number of days between two dates excludes consideration of the time. That’s the business requirement we’ll use. The days between February 1 and February 10 are 9 regardless of time—the time of one date could be 0100 and the other 2300 hours, but it’s still 9 days. JavaScript dates, however, include time, so there needs to be an adjustment.

Date.prototype.getDaysBetween = function(d) {   d = d.copy();    d.setHours(this.getHours(), this.getMinutes(), this.getSeconds(), ...     this.getMilliseconds());    var diff = d.getTime() - this.getTime();   return (diff)/this.msPERDAY; }; 

In this code, a new date is created with the same value as the argument, to avoid altering the original date. The time part of the new date is set to match the time of the date calling the method, eliminating the influence of the time of day.

The method is used like this:

var today = new Date(); var birthday = new Date(2008, 9, 31); var days = today.getDaysBetween(birthday);  if (days > 0)   alert(days + " days 'til my birthday."); else if (days < 0)   alert(days + " days since my birthday."); else   alert("It's my birthday!!"); 

If the date passed as an argument is later than the date used to call the method, a positive value is returned. A negative value is returned when the argument is an earlier date. An absolute value could have been returned, but knowing which date is earlier may be important, as in the example.

Calculating the Day of the Year

Combining getDaysBetween() and the technique used to calculate the last day of the month, we can create a method to calculate the day of the year (1 through 366) for a date:

Date.prototype.getDayOfYear = function() {   var start = new Date(this.getFullYear(), 0, 0);   return this.getDaysBetween(start) ∗ -1; }; 

Since there is no zero day of year, the date in question is compared to the day before January 1st: December 31st. The first line creates a Date instance with the value December 31st of the preceding year. The starting date is created using the same technique used for the last day of the month method. The first zero is January and the second is the day of the month number, which results in the day before January 1st.

Because the getDaysBetween() method returns a negative number when the argument is earlier, it is multiplied by minus one. The day of year should be a positive number.

The following code will return 65.

var date = new Date(2008, 2, 5); // 5th March 2008 alert(date.getDayOfYear()); 

Using Date Representations as an Argument

The getDaysBetween(d) method shown above accepts a Date object as its argument, but it may be more convenient to use other data types to represent a date. The Date constructor has four different invocations:

new Date(); // no argument, use current date and time new Date("Feb 20, 2008 10:20:05"); // string representation of the date new Date(2008, 1, 20, 10, 20, 05); // numbers representing the date new Date(milliseconds); // number of milliseconds 

Any of the methods we create that accept a date as an argument can be modified to accept any of the arguments recognized by the date constructor with the addition of the following code:

Date.prototype.getDaysBetween = function(d) {   var d2;    // Extra code for argument options   if (arguments.length == 0) {     d2 = new Date():   } else if (d instanceof Date) {     d2 = new Date(d.getTime());   } else if (typeof d == "string") {     d2 = new Date(d);   } else if (arguments.length >= 3) {     var dte = [0, 0, 0, 0, 0, 0];     for (var i = 0; i < arguments.length; i++) {       dte  [i] = arguments[i];     }     d2 = new Date(dte[0], dte[1], dte[2], dte[3], dte[4], ...       dte[5]);   } else if (typeof d == "number") {     d2 = new Date(d);   } else {     return null;   }    if (d2 == "Invalid Date")     return null;   // End of extra code    d2.setHours(this.getHours(), this.getMinutes(), ...     this.getSeconds(), this.getMilliseconds());    var diff = d2.getTime() - this.getTime();   return (diff)/this.msPERDAY; }; 

If the argument passed doesn’t convert to a date, the constructor creates a date instance with the value “Invalid Date”. In that case, null is returned.

(We’ll always assume that the argument is a date, to keep the article from wandering.)

Adding Days, Weeks, Months, and Years to a Date

Here are four methods—addDays(), addWeeks(), addMonths(), and addYears()—to change a date by adding (or subtracting) a number to the date. Each method takes a numeric argument representing the number of days, weeks, months, or years to be added as appropriate for the method. The code for the methods is straight forward.

Date.prototype.addDays = function(d) {   this.setDate( this.getDate() + d ); };  Date.prototype.addWeeks = function(w) {   this.addDays(w ∗ 7); };  Date.prototype.addMonths= function(m) {   var d = this.getDate();   this.setMonth(this.getMonth() + m);    if (this.getDate() < d)     this.setDate(0); };  Date.prototype.addYears = function(y) {   var m = this.getMonth();   this.setFullYear(this.getFullYear() + y);    if (m < this.getMonth()) {     this.setDate(0);   } }; 

The first method, addDays(), uses the same principle as the lastDay() method. The date object’s getDate() method returns the number of the day of month (1 through 31). The number of additional days is added to that, and then the Date object’s setDate() method sets the day of month to the new day. When a number used for a date exceeds (or is less than) the number of days in the month, JavaScript counts days foreward (or backwards) to the correct date.

The method addWeeks() converts the weeks to days and then uses the addDays() method to change the date. If, for example, the date is a Wednesday, the new date will be a Wednesday.

The methods addMonths() and addYears() work like addDays(). They use the Date object’s getMonth() and setMonth() or getFullYear() and setFullYear() methods respectively. The methods have an adjustment to accommodate unequal month or year lengths.

When adding months, one would expect the new date to be the same day of the month—if a month is added to January 2nd of some year, the results should be February 2nd—but, if a month is added to January 31st, the result, without adjustment, is March 3rd (March 2nd in leap years). For our purposes, it should be the last day of February, so there is a test to determine if the resulting day of month is less than the original date. If it is, that indicates the date was pushed into the month after the one we want. The fix uses the same technique as the lastDay() method: the date is set to the zero day.

The method addYears() has a similar issue in leap years. When adding a year to February 29th the results is March 1st, so it needs to be moved back to the 28th.

The methods can be used like this:

var date = new Date(2008, 1, 1); // 1st February, 2008 alert(date.addDays(7)); alert(date.addWeeks(3)); alert(date.addMonths(2)); alert(date.addYears(-2)); 

The alert boxes display February 8, 2008, February 29, 2008, April 29, 2008, and April 29, 2006.

Adding Week Days

In some business applications, only weekdays are counted—it might be an issue when calculating a project completion date and you don’t want to work weekends! This next method adds a number of weekdays, adjusted for weekends, so the period between the original date and the new date includes the required number of weekdays.

Date.prototype.addWeekDays = function(d) {   var startDay = this.getDay();  //current weekday 0 thru 6   var wkEnds = 0;  //# of weekends needed   var partialWeek = d % 5;  //# of weekdays for partial week    if (d < 0) {  //subtracting weekdays     wkEnds = Math.ceil(d/5); //negative number weekends      switch (startDay) {     case 6:  //start Sat. 1 less weekend       if (partialWeek  0 && wkEnds < 0)         wkEnds++;       break;     case 0:  //starting day is Sunday       if (partialWeek  0)         d++;  //decrease days to add       else         d—;  //increase days to add       break;     default:       if (partialWeek <= -startDay)       wkEnds—;     }   }   else if (d > 0) {  //adding weekdays     wkEnds = Math.floor(d/5);     var w = wkEnds;     switch (startDay) {     case 6:       // If staring day is Sat. and       // no partial week one less day needed       // if partial week one more day needed       if (partialWeek 0)         d--;       else         d++;       break;     case 0:       //Sunday       if (partialWeek 0 && wkEnds > 0)         wkEnds—;       break;     default:       if (5 – day < partialWeek)         wkEnds++;     }   }    d += wkEnds ∗ 2;   this.addDays(d); }; 

The method addWeekDays() calculates the number of weekend days that will need to be in the date range, and adds that to the required weekdays. That sum is added to the date using our addDays() method. addWeekDays() always produces a date between Monday and Friday inclusive. For example: it’s Saturday, and we’re finishing the project plan for a project that starts Monday. We’ve determined the project will take 50 days and want to calculate the completion date. The following code will calculate the date.

var today = new Date(2008, 1, 23); var endDate = today.copy(); endDate.addWeekDays(50); alert(endDate); 

The alert box will display May 2, 2008.

Unfortunately, management now decide that the project should be pushed back so it will finish on October 31st. They want to know when you need to start.

var endDate = new Date(2008, 9, 31); var startDate = endDate.copy(); startDate.addWeekDays(-50); alert(startDate); 

The alert box will display August 22, 2008; the latest the project can start and reasonably be expected to finish on the last day of October.

This does not take into account holidays or other special days the business is closed. To account for holidays, we can include addWeekDays() in a loop that increases the required days by one for every holiday in the date range from the starting date through the ending date. Here is an example function:

function due_date(start_date, workDays) {   var dueDate = new Date();   var days = 0;   var holidays = 0;    do {     dueDate.setYear(start_date.getFullYear());     dueDate.setMonth(start_date.getMonth());     dueDate.setDate(start_date.getDate());      days = workDays + holidays;     dueDate.addWeekDays(days);      // Your own lookup.     // Search database or array for     // holidays between start_date and dueDate     holidays = [query-results]    } while (days != workDays + holidays);    return dueDate; } 

(The due_date() function isn’t made a method of the Date object because it requires an external data source that is likely to change.)

The function due_date() assumes there is a data source (a database table or array) with the dates of all your company’s holidays, and that you have some way to query this table to return the number of holidays that occur between two dates.

The loop starts by setting dueDate to start_date. It adds the holidays (initially zero) to the business days and uses the addWeekDays() method to get a due date. The query gets the number of holidays between the start date and the due date (excluding any that are on Saturday or Sunday). If the number of holidays plus the original number of business days equals the number of days used to calculate the due date, the work is finished. Otherwise, the due date is reset and the loop runs again with the new number of holidays.

Calculating the Time Between Two Dates

Many business applications need to determine the time between two dates in units of days, months, years, or weekdays. We’ve already created a method to calculate the days between two dates: getDaysBetween().

A companion to addWeekDays() is getWeekDays(). It calculates the number of weekdays between two dates. Like addWeekDays(), this method does not take holidays into account, but it could be wrapped in a function that does.

Date.prototype.getWeekDays = function(d) {   var wkEnds = 0;   var days = Math.abs(this.getDaysBetween(d));   var startDay = 0, endDay = 0;    if (days) {     if (d < this) {       startDay = d.getDay();       endDay = this.getDay();     } else {       startDay = this.getDay();       endDay = d.getDay();     }     wkEnds = Math.floor(days/7);      if (startDay != 6 && startDay > endDay)       wkEnds++;      if (startDay != endDay && (startDay  6 || endDay  6) )       days-;      days -= (wkEnds ∗ 2);   }   return days; }; 

The bulk of the code determines how many weekend days need to be subtracted from the total number of days between the two dates. Also, unlike other methods, it returns an absolute value instead of a signed number. It is used like this:

var endDate = new Date(2007, 11, 5); // 5th December 2007 var startDate = new Date(2008, 1, 20); // 20th February 2008 alert(startDate.getWeekDays(endDate)); 

The alert box displays 55, the number of weekdays between the two dates.

A simple algorithm to calculate months between two dates might look like this:

var d1 = this.getFullYear() ∗ 12 + this.getMonth(); var d2 = d.getFullYear() ∗ 12 + d.getMonth(); return d2 - d1; 

That would work for dates spanning several years where fractions of a month are not significant.

Calculating the months between two dates is complicated by the partial month for each date—reasonably, there is more than one month between January 1st and February 28th. The days to be included as a partial month depend on the chronological order of the dates; we either need the days from the date to the end of the month, or from the 1st of the month to the date. We also want it to return a negative value if the date passed as the argument is the earlier of the two.

Date.prototype.getMonthsBetween = function(d) {   var sDate, eDate;   var d1 = this.getFullYear() ∗ 12 + this.getMonth();   var d2 = d.getFullYear() ∗ 12 + d.getMonth();   var sign;   var months = 0;    if (this == d) {     months = 0;   } else if (d1 == d2) { //same year and month     months = (d.getDate() - this.getDate()) / this.lastday();   } else {     if (d1 <  d2) {       sDate = this;       eDate = d;       sign = 1;     } else {       sDate = d;       eDate = this;       sign = -1;     }      var sAdj = sDate.lastday() - sDate.getDate();     var eAdj = eDate.getDate();     var adj = (sAdj + eAdj) / sDate.lastday() - 1;     months = Math.abs(d2 - d1) + adj;     months = (months ∗ sign)   }   return months; }; 

The two dates are converted to a number of whole months from a common point—year 1. Next the code branches based on the chronological order of the dates. If the dates are the same, the number of months is 0. If the dates are the same year and month, the number of months is the difference between the dates divided by the number of days in the month. Otherwise, reference variables are created indicating which date is the earlier. After that, the number of days left in the earlier date is calculated, the number of days in the later month is calculated, which is the month day, is calculated, and the sum is divided by the number of days in the earlier of the two months. (Phew!)

The number of days in the earlier month is used as the divisor because the sum will equal the number of days in the earlier month if the days are the same.

Having created getMonthsBetween(), it is easy to write a method to calculate the years between two dates. All that is necessary is to divide the months between the dates by 12:

Date.prototype.getYearsBetween = function(d) {   var months = this.getMonthsBetween(d);   return months/12; }; 

A special purpose method, getAge(), can be written using the method getYearsBetween() like this.

Date.prototype.getAge = function() {   var today = new Date();   return this.getYearsBetween(today).toFixed(2); }; 

And, you can use it like this:

var dateOfBirth = new Date(yob, mob, dob); var age = dateOfBirth.getAge(); 

The last method, sameDayEachWeek(), is a little different. It returns an array of dates for a given day of week—Sunday through Saturday—for each week between two dates. This could be used in an application scheduling recurring events.

Date.prototype.sameDayEachWeek = function (day, date) {   var aDays = new Array();   var eDate, nextDate, adj;    if (this > date) {     eDate = this;     nextDate = date.copy();   } else {     eDate = date;     nextDate = this.copy();   }    adj = (day - nextDate.getDay() + 7) %7;   nextDate.setDate(nextDate.getDate() + adj);    while (nextDate < eDate) {     aDays[aDays.length] = nextDate.copy();     nextDate.setDate(nextDate.getDate() + 7);   }   return aDays; }; 

The method takes a day-of-week value (0 through 6 for Sunday through Saturday) and a date as arguments. The first section of code calculates which date is the earlier date. It creates a date to increment, nextDate, which is a copy of the earlier date, as a starting point, and a reference to the later date as the ending date. A new Date object is used for nextDate so it can be changed without affecting the original date.

Next the date of the first week’s day we are looking for is calculated It is necessary to subtract from day before adding—subtraction casts a string to a number (if a string is passed) so the numbers will be added and not concatenated.

After that, a loop advances nextDate seven days each pass until the date is no longer in range. Each pass adds a new Date object to the array returned.

The method would be used like this:

var enddate = new Date(2008, 0, 5); // 5th January 2008 var date = new Date(2008, 1, 10); // 10th February 2008  var listofdays = date.sameDayEachWeek(2, enddate); // 2 = Tuesday alert("Tuedays in range are:nn" + listofdays.join("n")); 

The alert box displays the following.

Tuedays in range are:  Tue Jan 08 2008 00:00:00 GMT-0600 (Central Standard Time) Tue Jan 15 2008 00:00:00 GMT-0600 (Central Standard Time) Tue Jan 22 2008 00:00:00 GMT-0600 (Central Standard Time) Tue Jan 29 2008 00:00:00 GMT-0600 (Central Standard Time) Tue Feb 05 2008 00:00:00 GMT-0600 (Central Standard Time) 

Wrapping up

Many of the methods presented can be used without the others. Keeping in mind some methods are dependent on copy(), lastday(), getDaysBetween(), and getMonthsBetween(), and some are dependent on the three properties created, you can implement only the code your project needs.

Methods can be added to any of the other built-in object constructors—Array, String, Math, Object—using the same technique: assigning them to the prototype property.

I hope you find these methods useful in your work, and that I have shown how easy it is to extend JavaScript’s built-in objects with your own purpose-built code. Adding methods through the prototype gives your code clarity and some performance benefit (due to the way JavaScript resolves object references—it first searches local objects and then works its way down the prototype chain; global space is the last place JavaScript looks).

Source code

Download all the examples in a single file and use my user-defined methods in your own site or application:

ZIP file containing source, minified and packed versions

To include the file, simply refer to it in the <head> (or at the bottom of the <body>) of your document:

<script type="text/javascript" src="path/to/file/dates.js"></script> 

Or check out the interactive demo to see the various functions in action.

Further reading

Related Topics: Scripting, Prototyping

“Lawrence O’Sullivan”: cut his IT teeth as an xBase programmer, mostly CA Clipper, and has held a variety of positions including management and free lance development.