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

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

Using moment localeData you can get localized longDateFormat. This will give you localized format for year, month and day. You can use this value to parse your input string locale-aware.

Here a live example:

// Get user locale
var locale = window.navigator.userLanguage || window.navigator.language;
// Set locale to moment
moment.locale(locale);

// Get locale data
var localeData = moment.localeData();
var format = localeData.longDateFormat('L');

var m1 = moment('2/2/2016', format);
console.log(m1.format()); // February 2nd 2016
console.log(m1.format(format) + ' using format: ' + format);

var m2 = moment('5/1/2017', format);
console.log(m2.format());
console.log(m2.format(format) + ' using format: ' + format);
// January 5th 2017 for locales that use DD/MM/YYYY
// May 1st 2017 for locales that use MM/DD/YYYY
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>

This code will not work for locales that uses format that starts with year (e.g. YYYY.MM.DD. for Hungarian locale)


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'