SiteExperts.com Logo Home | Community | Developer's Paradise | Jobs
User Groups | Site Tools | Site Information | Search

Inside Technique : Date Methods
By Scott Isaacs

This demonstrates addings three new methods to the JavaScript Date Object.

Date.weekOf([boolean])This method returns a new date that represents the first day of the week for the date. The optional argument specifies whether the week starts on a sunday or monday. The default is sunday.
Date.strDay()Returns the day as a string.
Date.strMonth()Returns the month as a string.

Below demonstrates these new methods:

This page was created the week of

Demonstration Code

 // Outputs the week this page was created
 var d = new Date("8/9/1997");
 d  = d.weekOf();
 document.write(d.strDay() +", " + d.strMonth() +" " + d.getDate()+".")

Date Methods Code

 // The following code adds three methods to the built-in Date object
 function _strMonth() {
  var months = new Array("January", "February", "March", "April",
     "May", "June", "July", "August", "September", "October", 
     "November", "December");
  return months[this.getMonth()];
 }

 function _strDay() {
  var days= new Array("Sunday", "Monday", "Tuesday", "Wednesday", 
      "Thursday", "Friday", "Saturday");
  return days[this.getDay()];
 }

 function _weekOf() {
  sunday = ((arguments[0]==null) || (!arguments[0])); // Check for optional argument
  return (new Date(this - ((this.getDay() - ((sunday) ? 0 : 1)) *24*60*60*1000)));
 }

 // Add these methods to all dates
 Date.prototype.weekOf = _weekOf;
 Date.prototype.strMonth = _strMonth;
 Date.prototype.strDay = _strDay;
Discuss and Rate this Article