JavaScript Dates made localizable – Moment.js

Moment.js

Good library to make localizable JavaScript Dates is Moment.js. Through nuget it can be searched as „moment.js”.

Except regular dates output like:

Wednesday, November 27 2013 8:15 AM

it can also

2 years ago
in 16 hours
Last Sunday at 8:25 AM

Somewhere on the top of script you put a code that sets current language:

moment.lang('<%# ContentLanguage.PreferredCulture.TwoLetterISOLanguageName %>');

TwoLetterISOLanguageName was mapped to correct Moment.js language identifiers for 6 languages our app is supporting. I think it is the same for all languages.

Function that takes date from .NET through WebAPI:

var formatMeNice = function(value) { // value is in format: /Date(1245398693390)/  
    var newDate = moment(value);
                              
    var formatted = newDate.format('MMMM Do YYYY, h:mm:ss a'); 
    // November 25th 2013, 10:28:47 pm

    return formatted;
};

Formatting is similar to what we know from .NET

We needed to put localized dates for events on a page. Data was retrieved using ajax and we needed to format it on the client side. (First approach was to format it on backend as I know how to do it. It turns out that after WebAPI call the language information is lost and more parameters would be needed to be sent to ajax, so I chosen to do it on client side.)

.NET DateTime in JavaScript

Just a side note as we don’t need it today. First thing is that .NET serializes DateTime so it looks like something /Date(1245398693390)/ in JavaScript. To have JavaScript Date you need to do:

var date = new Date(parseInt(jsonDate.substr(6)));
Advertisements
Ten wpis został opublikowany w kategorii EpiServer i oznaczony tagami , . Dodaj zakładkę do bezpośredniego odnośnika.

Jedna odpowiedź na „JavaScript Dates made localizable – Moment.js

  1. Łukasz K. pisze:

    in old project I did something like that:
    page.ClientScript.RegisterStartupScript(typeof(Page), „JS_LANG”, string.Format(„var {1} = \”{0}\”;”, Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToLower(), „JS_LANG”));

    and then:
    $.datepicker.setDefaults($.datepicker.regional[JS_LANG]);

Możliwość komentowania jest wyłączona.