Date input and toLocaleDateString using different locales - javascript

I reside in Canada, where we format our dates dd/mm/yyyy. I'm seeing something unusual when I'm calling toLocaleDateString()
HTML:
<input type="date" value="2016-01-13">
<p id="container">
</p>
JS:
var d = new Date("2016-01-13");
document.getElementById('container').innerText = d.toLocaleDateString();
The value of the date input is what I would expect - 2016-01-13.
The value of the paragraph is the American format - 12-01-2016 (the change in day is due to localizing from GMT to EST)
Chrome language is set to Canadian, as is my system setting (Windows 7). The date input seems to be respecting that, but I thought toLocaleDateString() would pick up Canada as my locale and format the date appropriately.
MSDN describes this function like this:
dateObj.toLocaleDateString( [locales][, options])
locales (Optional). An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
Is the JavaScript runtime default locale something the user can change? I'm guessing not given my lack of success.
The different formatting between the date input and toLocaleDateString is quite baffling to me, any thoughts on how I can align the two?
http://jsfiddle.net/DfkU5/283/

Is the JavaScript runtime default locale something the user can change?
That depends entirely on the browser developers, they can do whatever they like. However, they tend to use system settings, but not always. Chrome ignores my settings for toLocalString, showing dates in m/d/y format when my preference is for d/m/y.
Safari, Chrome and Firefox all show a different string for toLocaleDate, which makes it just about useless.
The different formatting between the date input and toLocaleDateString is quite baffling to me, any thoughts on how I can align the two?
By far the best solution is to present dates in an unambiguous format, the easiest being to use the month name. All the following are unambiguous and easy to read:
19-Mar-2016
March 19, 2016
19 March, 2016
To do that you can write your own formatter (maybe 10 lines of code), or perhaps use a library.
In regard to input type date, not all browsers support it and there are lots of issues, so if you're going to use it you must check for support (fairly trivial) and if lacking, provide a fallback that does something sensible. And once you have a good fallback, you might as well implement it everywhere and forget input type date.
Then all the issues associated with it are gone. ;-)

Pass your locale as an arugment to toLocaleDateString()
e.g:
date.toLocaleDateString('en-CA')
or if you want to specify some fallback language, do this
date.toLocaleDateString(['en-CA','en-US'])
Check here

Related

How to set website-global hourCycle option

In many places in our project date formatting is being used. Dates is being formatted in 3-rd party libraries (such as SyncFusion EJ2 for example), and it's impossible unfortunately to define explicit format everywhere.
In Firefox hours is displayed in 0-23 format (which is fully correct). However, Chrome use 1-24 format for hour displaying.
Is there are any possibility to set hourCycle variable in Intl.DateTimeFormat globally which should affect all the page locale parameters?
Thank you very much

Time (hour, minute) format localization in moment.js

As momentjs has the ability take into account the date format for differernt locales, does it have the ability to localize time (hour:minute) format?
According to oracle docs time format there're some time format difference across region
https://docs.oracle.com/cd/E19455-01/806-0169/overview-6/index.html
moment().locale(somelocale).format('L') this will output the formatted date
However
moment().locale(somelocale).format('LT') doesn't seem like to have the same ability?
class TimeFormatter extends React.Component {
render() {
const browserLocale = window.navigator.userLanguage || window.navigator.language;
return (
<div>
{moment(this.props.value, 'HH:mm').locale(browserLocale).format('LT')}
</div>);
}
}
Above is my code for formatting the time cell on react data grid, but while I change the chrome settings the format stays the same.
So if I want to achieve time format localization can I use momentjs or I have to just come up a if else condition for setup specific user region time format
Many Thanks
The LT format does take locale into account.
Here are some examples:
moment().locale('en-CA').format('LT') //=> "1:21 PM"
moment().locale('fr-CA').format('LT') //=> "13:21"
moment().locale('fi-FI').format('LT') //=> "13.21"
moment().locale('de-DE').format('LT') //=> "13:21"
moment().locale('no-NO').format('LT') //=> "1:21 PM"
moment().locale('th-TH').format('LT') //=> "13:21"
moment().locale('en-GB').format('LT') //=> "13:21"
Note that the Oracle page you linked to is part of the Solaris 8 documentation - an operating system which came out in February 2000 and reached end of life in March 2012. It is sorely mistaken with regard to the time formats used in those countries and languages. You should not use it as a reference.
Also note that that it made a grave error in assuming that "Canadian" was enough to identify a locale completely. As shown above, French speaking Canadians use a 24-hour clock, but many English speaking Canadians sometimes use a 12-hour clock (see Time notation in Canada) and thus en-CA gives the 12-hour format while fr-CA gives the 24-hour format.
Thus, country alone is not enough. A locale must consist of at least language, but usually both language and country are necessary. These are now called "IETF language tags" and are standardized by BCP 47.
As far as why Moment's German localization doesn't include the string Uhr in the result, that was something that was first added with #1601, but then removed with #2006 - both back in 2014. See those issues for reasoning.
Also note that Moment's localization strings come from community submitted feedback and moment contributors. In many cases they align to the standards collated by Unicode CLDR, but in some cases they differ. If you are looking for a modern date library with standardized localization support, consider Luxon which leverages the internationalization APIs built into modern browsers.

Determine whether user is likely to be typing in dd/mm or mm/dd

I have an input date field on a webpage which allows the users to type in a date in various common acceptable formats.
The user can however enter a date like 10/11/12. This could mean 10 November 2012 or 11 October 2012. Is there a way to determine which of thes etwo they are likely entering without prompting them each time depending on their locale etc. I looked at using javascript toLocaleDateString but the output formats vary greatly between different browsers.
Would there be another way to determine this information ? I would maybe need to determine if they are based in the US or not.

How does toLocaleDateString() work in Chrome?

I understood the javascript method toLocaleDateString() used computer settings.
Let's take the W3Schools example :
when i change date and hour formats of my computer, the result is different in Firefox or IE (as expected), but Chrome still shows the same date format, why?
From the MDN:
"The exact format depends on the platform, locale and user's settings."
And,
"You shouldn't use this method in contexts where you rely on a particular format or locale."
Basically, "Why" is because that's how Chrome does it. If you need a specific format, you're going to have to specify it yourself.
From the EMCAScript 5 standard:
15.9.5.6 Date.prototype.toLocaleDateString ( )
This function returns a String value. The contents of the String are implementation-dependent, but are intended to represent the “date” portion of the Date in the current time zone in a convenient, human-readable form that corresponds to the conventions of the host environment’s current locale.
Chrome can represent the date as a locale date string in whatever manner it likes. The standard only supplies guidelines; it does not mandate a particular format. And, in fact, the result will vary not only between browsers but also within Chrome itself depending on your locale settings.
It looks like Chrome does not use the Windows regional settings, but its own settings instead. These are available via Settings > Advanced Settings > Language. However the date format is not explicitly defined, it is inferred from the language + country choice, for instance:
English (US) sets date format to mm/dd/yyyy
English (UK) sets date format to dd/mm/yyyy
(For anyone trying to change these, don't forget - like I did - to restart Chrome for the settings to take effect)
Back to the original question, it looks like it was legit to use toLocaleDateString() as long as the idea is to present the information in a format the human user understands. But this would be an ideal world, where every user has his/her browser properly configured. Instead, Chrome is set by default to English(US) as long as people leave it be in English, and it takes some googling (which most users won't do) to change these settings.
This makes it risky to use toLocaleDateString() even when not "relying on a particular format or locale". It looks like the only "serious" option for any cross-browser web application is to manage its own date format preferences (per user, of course...)

How to find browser date time format [duplicate]

I have set a deadline in UTC, as shown below, and I'm wondering what exactly the toLocaleString() method will do to it on user's local machines. For instance, will it account for daylight savings if they are in a timezone that recognizes it? Or will I need to insert additional code that checks where the user is, and then fixes the displayed time?
http://javascript.about.com/library/bldst.htm
var deadline = new Date('5/1/2013 ' + "16:15" + ' UTC');
alert(deadline.toLocaleString());
In general, the answer is yes. JavaScript will represent the UTC value at the appropriate local time based on the time zone settings of the computer it is running on. This includes adjustment for DST. However, as others have pointed out, the details are implementation specific.
If you want a consistent output, I would use a library to format your dates instead of relying on the default implementation. The best library (IMHO) for this is moment.js. The live examples on their main page will give you an idea of what it can do.
UPDATE
If you are passing UTC values that you want converted to the correct local time, and that time falls into a period where the time zone rules are different than the current one - then the results will be invalid. This is crazy, but true - and by design in the ECMA spec. Read - JavaScript Time Zone is wrong for past Daylight Saving Time transition rules
We don't know what exactly the toLocaleString method does (§15.9.5.5):
This function returns a String value. The contents of the String are
implementation-dependent, but are intended to represent the Date in
the current time zone in a convenient, human-readable form that
corresponds to the conventions of the host environment’s current
locale.
But yes, most implementations will consider DST if it is active in the current local timezone. For your example I'm getting "Mittwoch, 1. Mai 2013 18:15:00" - CEST.
Will I need to insert additional code that checks where the user is, and then fixes the displayed time?
I think you can trust toLocaleString - the browser should respect the user's settings. If you want to do it manually, check out timezone.js.
As you use "UTC" the date itself will be UTC format, but the toLocaleString() takes client's locale into account, which means it'll return the date in string updated with all and every changes typical to client's regional and locale settings (DST, date/time format, etc).As JS documentation describes this: "The toLocaleString() method converts a Date object to a string, using locale settings.".If you want to avoid this, use the toUTCString() method instead.I'd also recommend reading the accepted solution for the question Javascript dates: what is the best way to deal with Daylight Savings Time? to avoid (at least, to try to avoid :) future issues related to JS, browsers and locales.Hope this helps!

Categories