【问题标题】:Converting 'human' date string of different language to date object in JavaScript将不同语言的“人类”日期字符串转换为 JavaScript 中的日期对象
【发布时间】:2020-01-28 02:01:14
【问题描述】:

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

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

有没有办法识别其他语言的月份? 还是只能手动将月份翻译成英文?

【问题讨论】:

    标签: javascript node.js date translation


    【解决方案1】:

    很遗憾,没有用于此的原生 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(', ')));

    【讨论】:

    • 尝试在本地使用 Intl API,结果全部回退到英文。这会是兼容性问题吗?
    • 你需要给我更多关于你所做的事情的背景。
    • 将你的代码 sn-p 复制到一个 js 文件并使用 node (版本 12.13.0) 运行它
    • 哦,在 12.13 中不起作用,但在 v13.7.0 中起作用 nodejs.org/api/intl.html
    • @JamesRudolf 顺便说一句,对于 linux/macos,有node version manager 可以很容易地安装和使用指定的版本。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

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

        dbrekalo/translate-js

        【讨论】:

          【解决方案5】:

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

          [编辑]

          【讨论】:

          【解决方案6】:

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

          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

          【讨论】:

            猜你喜欢
            • 2018-08-20
            • 2011-03-07
            • 2022-07-20
            • 2020-05-21
            • 2020-11-30
            • 1970-01-01
            • 2019-01-31
            • 2012-01-28
            相关资源
            最近更新 更多