I am trying to determine users locale date format so that I can use it later to show date in specific format.
I know I can use toLocaleDateString()
to get the date format.
Let's say I got 1/2/2017
. How to determine whether this is in dd/mm
format or mm/dd
format?
One thing I have tried is I can get current date and month from new Date()
and check based on that (manually). When the date is 2/2/2016
or 3/3/2016
how to determine which one is date and which one is month?
Is there any solution anybody has for this issue?
Also I have looked into moment.js
. If some solution available there also I will be happy to use that.
You can do this without using moment also
function getDateFormatString() {
const formatObj = new Intl.DateTimeFormat(locale).formatToParts(new Date());
return formatObj
.map(obj => {
switch (obj.type) {
case "day":
return "DD";
case "month":
return "MM";
case "year":
return "YYYY";
default:
return obj.value;
}
})
.join("");
}
// locale="en-US"
getDateFormatString(); // MM/DD/YYYY
// locale="en-GB"
getDateFormatString(); // DD/MM/YYYY
Answering this for 2019. If you really want to be thorough, you can try to handle low market share legacy browsers, non-Latin numbering systems or non-Gregorian calendars.
This could all be reduced to a regex replace, but if you're going to be parsing dates, you're going to want to keep the field indices.
function dateFormat(language) {
const sample = window.Intl ? new Intl.DateTimeFormat(language, {
numberingSystem: 'latn',
calendar: 'gregory'
}).format(new Date(1970, 11, 31)) : '';
let mm = 0,
mi = sample.indexOf(12);
let dd = 1,
di = sample.indexOf(31);
let yy = 2,
yi = sample.indexOf(1970);
// IE 10 or earlier, iOS 9 or earlier, non-Latin numbering system
// or non-Gregorian calendar; fall back to mm/dd/yyyy
if (yi >= 0 && mi >= 0 && di >= 0) {
mm = (mi > yi) + (mi > di);
dd = (di > yi) + (di > mi);
yy = (yi > mi) + (yi > di);
}
let r = [];
r[yy] = 'yyyy';
r[mm] = 'mm';
r[dd] = 'dd';
return r.join(sample.match(/[-.]/) || '/');
}
console.log(dateFormat()); // 'mm/dd/yyyy' if in US
console.log(dateFormat('de')); // 'dd.mm.yyyy'
console.log(dateFormat('en-AU')); // 'dd/mm/yyyy'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With