Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
81
rated 0 times [  86] [ 5]  / answers: 1 / hits: 5209  / 4 Years ago, tue, january 28, 2020, 12:00:00

I am trying to convert the following set of strings:



juin 2016
septembre 2013
janvier 2013
juillet 2010



All of which are in French, so when I use new Date() it defaults to January:



new Date('juin 2016') // -> Fri Jan 01 2016 00:00:00
new Date('août 2013') // -> Tue Jan 01 2013 00:00:00


Whereas it should be:



new Date('juin 2016') // -> Wed Jun 01 2016 00:00:00
new Date('août 2013') // -> Thu Aug 01 2013 00:00:00


Is there a way for the months from other languages be recognized?
Or the only way is to manually translate the months into english?


More From » node.js

 Answers
3

Unfortunately there is no native API for this.



If you know the format, it is easy to convert, without a massive library:





const months = [janvier, février, mars, avril, mai, juin, juillet, août, septembre, octobre, novembre, décembre];

function getDateFromMonthYear(input) {
const parts = input.split( );
if (parts.length != 2) throw Error(`Expected 2 parts, got ${parts.length}: ${input}`);
const [searchMonth, year] = parts;
const month = months.indexOf(searchMonth.toLowerCase());
if (month < 0) throw Error(`Unknown month: ${searchMonth}`);
return new Date(year, month, 1);
}


[juin 2016, septembre 2013, janvier 2013, juillet 2010].forEach(date =>
console.log(
date,
-> ,
getDateFromMonthYear(date).toDateString()
)
);





There is a new Intl API that you can use to get the month-names of supported languages:





function getFullMonthName(locale) {
const int = new Intl.DateTimeFormat(locale, { month: long });
const out = [];
for (let month = 0; month < 12; ++month) out[month] = int.format(new Date(2020, month, 3));
return out;
}

[sv-SE, fr-FR, en-US, en-UK].forEach(locale => console.log(locale, getFullMonthName(locale).join(', ')));




[#4923] Friday, January 24, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kayden

Total Points: 546
Total Questions: 102
Total Answers: 95

Location: Virgin Islands (U.S.)
Member since Fri, Mar 4, 2022
2 Years ago
kayden questions
Sun, Sep 20, 20, 00:00, 4 Years ago
Wed, Oct 30, 19, 00:00, 5 Years ago
Mon, Mar 4, 19, 00:00, 5 Years ago
;