Javascript users incorrect locale with date formatting - javascript

In javascript I'm using Date.toLocaleDateString to format my dates in the user's locale. While in theory it should work, it doesn't.
I am located in the UK. My computer is set to UK and my default language is set to en/gb in both system settings and the browser content settings. Yet, Firefox always displays dates the US format. Is there some trick I'm missing?
The full code for formatting is this:
var timestamp = ...; //some value from ajax call
var dt = new Date(timestamp);
$('#audit-date').text(dt.toLocaleDateString());
In the UK for today's date I would expect to see 05/02/2014, but I see 02/05/2014, which is the US version of it.

Use this to pass the locale.
var locale = window.navigator.userLanguage || window.navigator.language;
alert(date.toLocaleString(locale));

A quick look into to awesome MDN Documentation tells me that you need a locale parameter, otherwise the result depends on the browser. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
// British English uses day-month-year order
alert(date.toLocaleString("en-GB"));
// → "20/12/2012 03:00:00"
For more custom date formats I use the moment.js library. http://momentjs.com/

Related

moment.js formatting date wrong

I'm trying to get upcoming date using moment.js. The date is obtained, but it's formatted wrongly. According to docs, format('l') formats the date in dd/mm/yyyy format and format('L') formats date in mm/dd/yyyy. but I'm getting the same output for both. Here is my code.
let next = moment().add(30, 'days').format('l'); // Output 10/16/2019
let next = moment().add(30, 'days').format('L'); // Output 10/16/2019
let next = moment().add(30, 'days').format('DD/MM/YYYY'); // Works fine
I tried i with moment.js v2.24.0 what's wrong in here? am I missing something or doing it wrong way?
According to docs, format('l') formats the date in dd/mm/yyyy format and format('L') formats date in mm/dd/yyyy.
No, that isn't what the documentation says:
Localized formats
Because preferred formatting differs based on locale, there are a few tokens that can be used to format a moment based on its locale.
There are upper and lower case variations on the same formats. The lowercase version is intended to be the shortened version of its uppercase counterpart.
Month numeral, day of month, year: L 09/04/1986
l 9/4/1986
There's nothing there saying L will use one field order and l another.
It's using your current Moment locale to format the date. See the i18n section for how to set locales, globally or per instance.
According to docs
moment().format('L'); // 09/16/2019
moment().format('l'); // 9/16/2019
https://momentjs.com/

Get the given date format (the string specifying the format) in javascript or momentjs

Given a datestring, how can I get the format string describing that datestring?
Put another way, how can I get the format string that Date() or MomentJS (might be different for each, that's fine) would use to parse that datestring if one didn't pass an explicit format to use?
So given '2016-01-01' it should output something like 'YYYY-MM-DD', for example.
(I am aware this is a simple question and may have an answer somewhere, but it is difficult to word concisely, so I could only find questions and answers about how to parse datestrings or how to display dates. None about how to output the format itself.)
Consolidating information from Matt Johnson's answer, some comments, and my own contribution.
With Moment.js (version 2.10.7+), you can use the Creation Data API. Something like this in Node.js:
moment('2016-01-01 00:00:00').creationData().format
outputs
'YYYY-MM-DD HH:mm:ss'
Just as any date parsing is, there is ambiguity about the format of many datestrings due to things such as locale (the order of months and days are switched between the US and Europe, for example). But the above method is sufficient for me.
You can't, without having additional information, such as the locale. For example, 01/12/16 could be Jan 12, 2016, December 1, 2016, or December 16, 2001.
Even when you know the locale, there are several places in the real world where more than one date format is used, depending on context.
See https://en.wikipedia.org/wiki/Date_format_by_country
However, if you are just trying to determine which one of multiple known formats was used to parse the input string, moment has an API for that called Creation Data. For example:
var m = moment("2016/06/10", ["YYYY-MM-DD", "MM/DD/YYYY"], true);
var f = m.creationData().format; // "MM/DD/YYYY"

Moment.js : Format date according browser lang

I use this code to display a date in French format :
var dateToDisplay = moment(myDateInMS, "x").format("DD/MM/YYYY - hh:mm:ss"); // Output : "20/03/2016 - 12:35:32"
I would like to improve this display to have a better display according the browser language. How can i do that using moment ?
I do not recommend setting the locale depending on the browser language as it's not a clear signal of the actual locale of the user. E.g. a user may use an English operating system even though s/he's a French speaker.
That being said. Reading the language from the browser and setting Moment.js to the corresponding locale can be done this way:
var localeData = moment.localeData();
switch (navigator.language || navigator.userLanguage) {
case 'fr':
localeData = moment.localeData('fr');
break;
}
localeData.longDateFormat('LL'); // the example 'LL' will output date in "D MMMM YYYY format"
Notice that this is setting the locale of the entire Moment.js instance (which is probably what you want to do). Also notice that as of Moment.js 2.8.0, changing the global locale doesn't affect existing instances.
Also see
Changing locale globally
Long Date Format
Moment will actually search for substrings of the locale pulled from the browser in an attempt to pick the correct locale. Thus, there is no need to preparse or create a case statement.
As an example, moment has es as a locale, but not es-mx. If the browser is set to es-mx the locale function looks for es-mx and when it doesn't find it, falls back to es. Thus:
moment.locale('es-mx');
"es"
Meaning that for your purposes you can just do:
moment.locale(navigator.userLanguage || navigator.language);
Then when formatting your dates, use one of the locale specific formats to make them appropriate for the user:
moment().format('LL')
"1 de abril de 2016"
moment().format('L')
"01/04/2016"
For all of the localized formats and what they should produce, see the localized format section of the format documentation: http://momentjs.com/docs/#/displaying/format/

toLocaleDateString() is not returning dd/mm/yyyy format

Hi I have used toLocaleDateString() to display a date from a rss feed,t its not showing dd/mm/yyyy format in all browser, safari and mozila its showing differently but chrome it is showing correctly.
toLocaleDateString is intended to provide a human-readable format, according to the rules of the user's own computer. For instance, if my computer is set to French, it might include the day name in French.
toLocaleDateString is NOT a reliable way of getting the format you want. Instead, do this:
var dateobj = new Date();
function pad(n) {return n < 10 ? "0"+n : n;}
var result = pad(dateobj.getDate())+"/"+pad(dateobj.getMonth()+1)+"/"+dateobj.getFullYear();
I was looking for an answer to this question, but above answers doesn't give a crip answer for converting date to dd/mm/yyyy using toLocaleDateString().
As per docs toLocaleDateString() converts a date to a string with a language sensitive representation of the date portion. This method accepts two parameters dateObj.toLocaleDateString( [locales][, options]) described below :
locales: This parameter is an array of locale strings that contain one or more language or locale tags.Note that it is an optional parameter.If you want to use specific format of the language in your application then specify that language in the locales argument.Some parameters are:
en-US : US English uses month-day-year order i.e 07/17/2020
en-GB : British English uses day-month-year order i.e 17/07/2020
ko-KR : Korean uses year-month-day order i.e 2020. 07. 17.
options: It is also an optional parameter and contains properties that specify comparison options.Some properties are localeMatcher, timeZone, weekday, year, month, day, hour, minute, second etc.
So using this here is how you can convert date to dd/mm/yyyy format:
let dateFormat=new Date().toLocaleDateString('en-GB', {
month: '2-digit',day: '2-digit',year: 'numeric'})
console.log(dateFormat)
for persian date (current date)
const p2e = s => s.replace(/[۰-۹]/g, d => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d))
const dateFormat = p2e(new Date().toLocaleDateString('fa-IR', { month: '2-digit', day: '2-digit', year: 'numeric' }))
console.log(dateFormat)
This has already been answered before:
According to the Mozilla documentation, the format can vary wildly depending on the user's location and computer settings.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
The exact format depends on the platform, locale and user's settings.
.toLocaleDateString() Not Working in Firefox
In Chrome you need to go to the Advanced>Language settings. Then drop down the top "Language" section and you will probably see a few variations of English.
Ensure that you select "Display Google Chrome in this language" for the version of English you want - it doesn't matter whether it is at the top of the list.

Manipulating dates in Javascript without the Date object

It appears I can't use the javascript Date object as it inherintly defaults to US dates when you initialise with a datestring. There is no way of passing any culture information to the date object
I.e. No matter what the clients locale settings are
var d = new Date("08/10/2009") will always create a date object representing the 10th August 2009 rather than the 8th October 2009 if the clients locale was the UK.
So given that my requirement is to be able to add/subtract days/months/years easily is there a clever way of doing this easily without the Date object
All i need to do is add a day to a date (or a string representation of a date). so if my code detects the locale setttings are in the US, when it sees a string like "10/08/2009" it whacks it up to "10/09/2009" but if it had detected it was in the UK it would have know it a uk string representation of a date and whacked it up to "09/10/2009"
For date manipulation and localization on JavaScript I always recommend the DateJS library.
This library abstracts the use of Date objects, has a very good localization options, powerful date parsing and formatting, and it also has a very nice fluent API.
If you know you are getting input formatted dd/mm/yyyy you can easily assemble the correct date.
function britDay(D){
D= D.match(/\d+/g);
return new Date(+D[2], D[1]-1, +D[0]);
}
toLocaleDateString will return the date in the format expected by the user.
Relying on the user input that obeys particular formatting rules is optimistic-
which is why most sites use separate, labeled inputs or select fields for the month, date and year.
You probably know that it's easy to add one day to a date, just add 86,400 * 1000 milliseconds to the date. It sounds like displaying in your locale is the issue; does Date.toLocaleString() not do the right thing for you?
dojo.date.locale.parse will be able to parse a formatted string according the locale of your choice. It has a table of cultural data based off unicode.org/cldr. See this article for more information.

Categories