Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine users locale date format using javascript (format is dd/mm or mm/dd)?

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.

like image 947
Shrabanee Avatar asked Apr 12 '17 11:04

Shrabanee


2 Answers

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
like image 148
Praveen Kumar Avatar answered Oct 14 '22 05:10

Praveen Kumar


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'
like image 26
Adam Leggett Avatar answered Oct 14 '22 05:10

Adam Leggett