How to format Scal's Date Output

Friday, September 21st, 2007

When you create the scal object, there is a parameter called update_id that you use to reference the HTML element you wish to update with the "clicked" day value. By default, this puts in a raw Javascript Date object. However, instead of providing the id of an HTML element you can also reference a function that can format the Date or really do anything you would like.

On the homepage, I use a function override to show the date in a normal format. If you do a View Source, you can see the example, but I will reproduce it below for reference:

samplecal = new scal('samplecal',updateyear,{titleformat:'mmmm yyyy',closebutton:'X',dayheadlength:2,weekdaystart:0});
// note that updateyear does not appear in quotes.
// This means that scal will call a function in my
// code named updateyear() when someone clicks on a cell.

function updateyear(){
   $('samplecal_value').update( samplecal.selecteddate.format('mmmm dd, yyyy'));
};

// Here is the sample update function.  I have a div in my HTML called samplecal_value.
// The updateyear() function, updates that value with the selecteddate property of the
// samplecal object (which is a Javascript Date object).

The format function above is actually an addition I made to the Date object. This is already included in scal.js.

As noted in the source, I borrowed this function from Hector Rivas's article at http://www.codeproject.com/jscript/dateformat.asp. I've reproduced that here so that you can see the various formats available to you when constructing your Date format.

Date.prototype.format = function(f)
	{
	    if (!this.valueOf())
	        return ' ';

	    var d = this;

	    return f.replace(/(yyyy|mmmm|mmm|mm|dddd|ddd|dd|hh|nn|ss|a\/p)/gi,
	        function($1)
	        {
	            switch ($1.toLowerCase())
	            {
	            case 'yyyy': return d.getFullYear();
	            case 'mmmm': return scalmonthnames[d.getMonth()];
	            case 'mmm':  return (scalmonthnames[d.getMonth()]).substr(0, 3);
	            case 'mm':   return (d.getMonth() + 1);
	            case 'dddd': return scaldaynames[d.getDay()];
	            case 'ddd':  return scaldaynames[d.getDay()].substr(0, 3);
	            case 'dd':   return d.getDate();
	            case 'hh':   return ((h = d.getHours() % 12) ? h : 12);
	            case 'nn':   return d.getMinutes();
	            case 'ss':   return d.getSeconds();
	            case 'a/p':  return d.getHours() < 12 ? 'a' : 'p';
	            }
	        }
	    );
	};
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • del.icio.us
  • Reddit
  • Slashdot
  • Technorati
  • description
  • NewsVine
  • StumbleUpon
  • E-mail this story to a friend!
  • Sphinn

Leave a Reply