Hot Date! | December 10th, 2007
I was just going over the Calendar component when I found some useful functionality that was all tucked away, obscured from prying eyes. But the time has come to unleash it upon you all!
1. Formatting
There’s a method, DatePicker#getFormattedDate that will return the selected date as a string in the ubiquitous ISO8601 format (YYYY-MM-DD HH:MM:SS).
What’s better still, you can customize the format returned by getFormattedDate by using the formatter attribute on the Calendar declaration to specify a custom formatting function.
The Function
Let’s say I want the Calendar to format dates like this: MM/DD/YYYY.
function customFormatter(date)
{
if (nitobi.base.DateMath.invalid(date)) return "";
return nitobi.lang.padZeros(date.getMonth() + 1) + "/" + nitobi.lang.padZeros(date.getDate()) + "/" + date.getFullYear();
};
A couple things to note here:
- First, it’s very important we ensure the date is valid.
- Second, we use a helper method nitobi.lang.padZeros to ensure single digits get padded correctly (e.g. “1″ will become “01″, but “10″ will remain “10″).
- Third, the argument is a Javascript Date object.
The Declaration
Next, we change our Calendar declaration and specify this custom function as the formatter:
<ntb:datepicker id="cal1" formatter="customFormatter"></ntb:datepicker>
Now when we call #getFormattedDate we’ll get a string of the form MM/DD/YYYY.
2. Hidden Inputs
Another useful tidbit is the Calendar renders with a hidden input field that will store the formatted date which makes using it in a form pretty simple. For a Calendar with an id of “calendar1″, the hidden input will have an id of “calendar1.value”.
Go figure!
May 23rd, 2008 at 9:46 am
The really great thing about that hidden input is that its “name” property is whatever id you gave the calendar component, so that’s what it will get posted as if you post the form. The guy who designed that must have been some kind of crazy genius! To note: making the “name” settable would also be a good idea.