views:

36

answers:

2

Hi All,

I have "Friday, April 02, 2010" as date now I want to display "04/02/2010" if browser language is selected english and "02.04.2010" if browser language is selected as German. All I want, is to display the date as per the browser format.

Any Idea how this can be done?

+2  A: 

It gets complicated fairly quickly, your best bet is to find a library to do it.

There's DateJS, for example, which is free and open and supports 150 or so locales, albeit with different files for each, which might be a pain in terms of converting your input format, if your input is always in English. If there's any chance you can change your input to be something internationalized like ISO 8601 (more here and here), that will make localizing that input a lot easier.

T.J. Crowder
@T.J, so there is no support inbuilt and I have to learn to use DateJS or such other javascript?
Vinay Pandey
@vinay_rockin: That depends on your definition of "built-in." For instance, you could parse that string yourself and then use the `Date(year, month, day)` constructor (not that that helps you much). The only built-in support for parsing date strings looks for a *very* specific format, unfortunately, see section 15.9 (particularly 15.9.1.15 and 15.9.4.2) of the spec: http://www.ecma-international.org/publications/standards/Ecma-262.htm (Note that older JavaScript implementations won't support that use of ISO 8601 and require an even more obscure date format.)
T.J. Crowder
Date(year,month ,day) will again give me "Friday, April 02, 2010", now how do I display as the selected browser date format of(mm/dd/yyyy or dd/mm/yyyy or similar ones have other seperators like :,- instead of /) which is the original question.
Vinay Pandey
@vinay_rockin: Hence my comment "not that that helps you much." :-) Again, you'll either have to hand-code this, or use a library. I strongly recommend using a library; no point in reinventing the wheel.
T.J. Crowder
@T.J, got that I will use one of the libraries as of now and see how it goes. Thanks a ton by the way if you find something helpful anytime in future please let me know.
Vinay Pandey
@vinay_rockin: Glad the helped.
T.J. Crowder
A: 
<html>
<body>
hi
<script>
var lang = navigator.language;
if (!lang) {
lang = navigator.userLanguage;
}
alert (lang);
if (lang.match (/^en/)) {
document.write ("04/02/2010");
} else if (lang.match (/^de/)) {
document.write ("02.04.2010");
} else {
document.write ("I give up");
}

</script>
</body>
</html>
Kinopiko
@Smack, so you mean there is no easy way out, and I should check for the languages targeting the larger audience?
Vinay Pandey
You want a general solution for all languages? I think the other answer looks good.
Kinopiko