FLighter
FLighter

Reputation: 439

How to set locale for parsing in moment.js?

Unfortunately, I didn't find the answer in the documentation, so...

For example, I have input date: "09/01/2017". I don't know, it is DD/MM/YYYY or MM/DD/YYYY, but I know user locale. Can I get something like below?

let date   = "09/01/2017",
    locale = "en_US",// or "en_AU"
    result = moment(date, locale).format("DD MMM YYYY");
// 01 Sep 2017
// 09 Jan 2017

Or do I need to write a map and than set a format to moment?

let map =
    {
        en_US: 'DD/MM/YYYY',
        en_AU: 'MM/DD/YYYY',
        // ...
    },
    date   = "09/01/2017",
    locale = "en_US",// or "en_AU"
    result = moment(date, map[locale]).format("DD MMM YYYY");
// 01 Sep 2017
// 09 Jan 2017

Thanks

Upvotes: 0

Views: 2193

Answers (2)

Zenkylo
Zenkylo

Reputation: 136

I'd use plain JS to pull the month based on local, use moment to format the month to MMM, then just join em up.

var locale = 'en_AU'

var date = '09/01/2019'.split('/')

if (locale === 'en_AU') {
    var monthFormatted = moment(date[0]).format('MMM')
    date = [date[1], monthFormatted, date[2]].join(' ')
}

else {
    var monthFormatted = moment(date[1]).format('MMM')
    date = [date[0], monthFormatted, date[2]].join(' ')
}

console.log(date)
// 09 Jan 2019 or 01 Sep 2019

Upvotes: 0

VincenzoC
VincenzoC

Reputation: 31482

You can use moment.localeData() and longDateFormat('L') do get locale specific tokens.

Here a live sample:

let date   = "09/01/2017";
let locale = "en_US";
let localeFormat =  moment.localeData(locale).longDateFormat('L');
let result = moment(date, localeFormat).format("DD MMM YYYY");
console.log(result); // 01 Sep 2017

locale = "en_AU";
localeFormat =  moment.localeData(locale).longDateFormat('L');
result = moment(date, localeFormat).format("DD MMM YYYY");
console.log(result); // 09 Jan 2017
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>

Upvotes: 3

Related Questions