how to determine year, month, day ordering based on locale?

I would like to display three custom dropdowns for the user to select year, month, and day of their identification card.

How can I determine which order to show the year, month, and day, using only JavaScript (not moment)?

Example output for en-US:

['month', 'day', 'year']

Example output for en-CA:

['year', 'month', 'day']

Answers:

Answer

function datePartOrder(locale) {
  const parts = new Intl.DateTimeFormat(locale).formatToParts();
  const filteredParts = parts.filter(part => ['year', 'month', 'day'].includes(part.type));
  const filteredPartNames = filteredParts.map(part => part.type);
  return filteredPartNames;
}

// examples:

console.log(datePartOrder('en-US')); //["month", "day", "year"] );
console.log(datePartOrder('en-CA')); //["year", "month", "day"]

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.