James Rudolf
James Rudolf

Reputation: 99

Converting 'human' date string of different language to date object in JavaScript

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?

Upvotes: 2

Views: 6582

Answers (6)

Mister Jojo
Mister Jojo

Reputation: 22320

you may use this for help:

const OnlyMonth  = { month: 'long' }
  ,   listMonths = Array(12).fill('').map((x,m)=>(new Date(Date.UTC(2000, m, 1, 1, 0, 0))).toLocaleDateString('fr-FR', OnlyMonth))
  ;
console.log( JSON.stringify(listMonths,0,2) )
.as-console-wrapper { max-height: 100% !important; top: 0; }

PS: https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes

Time having brought me a new look, it can also be written as follows (shorter code):

Array(12).fill('').map((_,m)=>new Date(`2000-${++m}-1`).toLocaleDateString('fr-FR',OnlyMonth))

Upvotes: 1

some
some

Reputation: 49612

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(', ')));

Upvotes: 1

100PercentVirus
100PercentVirus

Reputation: 17

Since it's the months that you want to translate, there might be no need for third party libraries. A simple workaround is as shown below:

var FrenchToEnglishMonths = 
{'janvier':'January','février':'February','mars':'March','avril':'April','mai':'May','juin':'June','juillet':'July','aout':'August',
'septembre':'September','octobre':'October','novembre':'November','décembre':'December'};  
var frenchDate  = 'juin 1,2016'; 
var frenchMonth = frenchDate.split(" ")[0].toLowerCase();//get the french month
var englishMonth= FrenchToEnglishMonths[frenchMonth];//find the corresponding english month
var englishDate = frenchDate.replace(frenchMonth,englishMonth);//replace the french month with the english month  
var date        = new Date(englishDate); //tadaa...

Upvotes: 1

prismo
prismo

Reputation: 1899

I would suggest you make use of moment js (momentjs.com/docs/#/i18n)

[EDITED]

Upvotes: 0

NobodyImportant
NobodyImportant

Reputation: 347

You can simply create an object to translate the months from French to English:

const frToEn = {
    "janvier":"january",
    "février":"february",
    "mars":"march",
    "avril":"april",
    "mai":"may",
    "juin":"june",
    "juillet":"july",
    "août":"august",
    "septembre":"september",
    "octobre":"october",
    "novembre":"november",
    "décembre":"december"
}

function getDate(input) {
    const date = input.split(" ");
    const month = frToEn[date[0].toLowerCase()];
    const year = date[1];
    return new Date(`${month} ${year}`);
}

getDate("juin 2016");
getDate("août 2013");

Upvotes: 2

Jonel Zape
Jonel Zape

Reputation: 42

You can use library for translating these months to English like

dbrekalo/translate-js

Upvotes: 0

Related Questions