Example: Formatting Dates Using Language Resource Bundles

The "date-format" module of the DataType Utility leverages the external language resource bundle support provided in 3.1.0, as the preferred way to define and deliver formatting patterns for various languages.

Default Date Formatting (no language specified):
Date Formatted for "fr-FR":
 

Using Date Formatting Support

To use Date formatting language resource bundle support in your application, all you need to do is use the datatype-date module, and specify the (supported) language you need for the instance.

// Default (no language specified)
YUI().use("datatype-date", function (Y) {
    Y.one("#default_lang_output").setHTML(
        Y.Date.format(new Date(), {format:"%x"})
    );
});

// Format Date For fr-FR
YUI({lang:"fr-FR"}).use("datatype-date", function (Y) {
    Y.one("#single_lang_output").setHTML(
        Y.Date.format(new Date(), {format:"%x"})
    );
});

Switching Languages

You can also switch the language resource bundle currently in use for your YUI instance, by invoking Y.use to pull down another language resource bundle if required:

...

var lang = Y.one("#demo_lang").get("value");

// Pull down a new language resource bundle for datatype-date.

// Since it's a potentially async operation, we write our application logic
// in a callback which is invoked once the new language resource bundle is pulled down

Y.use("lang/datatype-date-format_" + lang, function(Y) {

    // You only need to set the language explicitly when switching languages,
    // It is not required for the single language use case shown previously.
    Y.Intl.setLang("datatype-date-format", lang);

    formattedDate = Y.Date.format(new Date(), {format:"%c"});

});
...

The Y.Intl utility, which is automatically pulled down with a language resource bundle acts as a manager for language resource bundle handling, and is used to register new language resource bundles, set the language currently being used, and retrieve strings for the currently language.

Available Languages

The set of available languages for a given module, can be obtained from the Intl utility, and we use this support to generate the dropdown for this example:

// Insert the languages available for the datatype-date module
var availLangs = Y.Intl.getAvailableLangs("datatype-date-format"),
    select = Y.one("#demo_lang"),
    i;

for (i = 0; i < availLangs.length; i++) {
    select.append('<option value="' + availLangs[i] + '">' + availLangs[i] + '</option>');
}