Skip to Navigation | Skip to Content



Archive for December, 2007

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!

Posted in calendar, cui, features | 1 Comment » | Add to Delicious | Digg It


Search Posts

You are currently browsing the Mike’s Blog weblog archives for December, 2007.


My ideal work culture:
[See my summary] [What's yours?]

Archives

Categories