Javascript — Detect if user's locale are set to use 12-hour or 24-hour time format

后端 未结 5 2117
花落未央
花落未央 2021-01-04 09:02

One way to do that is to parse new Date().toLocaleString(). But this doesn\'t work in chromium/webkit since the string it returns isn\'t dependent of the user\'

5条回答
  •  -上瘾入骨i
    2021-01-04 09:52

    You should never search for local pattern this way. toLocaleString() is clearly a mistake (derived from Java) and should not be used. As you mentioned, this method is not well supported in various browsers (Chrome is just one of them).
    In fact the only web browser (from popular ones) which get it about right (but not 100% right) is IE.

    To correctly format date depending on Locale, please use Globalize. It contains localized patterns dumped out of .Net.
    You may alternatively want to use Dojo which also allows Locale-aware formatting, but based on CLDR.

    Edit, new facts exist

    There is a new standard for I18n in JavaScript - ECMA-402. This standard in fact allows for using JS Date's object. However, one should always pass a language tag:

    var date = new Date();
    var formatted = date.toLocaleString('de-DE');
    

    The only problem with this is, the only web browser I am aware of that currently implements ECMA-402 is Google Chrome.

    For now it seems that still the way to go is to use something along the lines of iLib.

提交回复
热议问题