将 'human' 不同语言的日期字符串转换为 JavaScript 中的日期对象

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

我正在尝试转换以下字符串集:

juin 2016 septembre 2013 janvier 2013 juillet 2010

所有这些都是法语的,所以当我使用 new Date() 时,它默认为 January:

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

而应该是:

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

有没有办法识别其他语言的月份? 或者唯一的方法是手动将月份翻译成英文?

我建议你使用moment js (momentjs.com/docs/#/i18n)

[编辑]

您可以使用库将这些月份翻译成英语,例如

dbrekalo/translate-js

您可以简单地创建一个对象来将月份从法语翻译成英语:

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");

遗憾的是,本机没有此功能 API。

如果你知道格式,就很容易转换,不需要海量的库:

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

有一个新的 Intl API 可用于获取受支持语言的月份名称:

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

由于您要翻译的是月份,因此可能不需要第三方库。一个简单的解决方法如下所示:

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...

你可以使用这个来寻求帮助:

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

时间给我带来了新的面貌,也可以这样写(更短的代码):

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