Javascript如何使用非英语字符串

时间:2018-05-15 19:54:55

标签: javascript

var date = new Date ("Mai 15, 2018 10:41:48"); 

该字符串是德语。 我收到错误"无效日期"正如所料,因为JS希望我用英语。

我不想使用toLocaleString(),因为我尝试使用其他语言初始化日期。

1 个答案:

答案 0 :(得分:4)

您可以使用moment.js https://momentjs.com/docs/#/i18n/

let localLocale = moment();

localLocale.locale('de'); // set this instance to use German
let date = localLocale.date("Mai 15, 2018 10:41:48").toDate();
console.log(date);

// if you don't want to add this dependency, you can do something like this 


let str = 'Mai 15, 2018 10:41:48';
const months = {
  Januar: 'January',
  Februar: 'February',
  'März': 'Macrh',
  Marz: 'March',
  April: 'April',
  Mai: 'May',
  Juni: 'June',
  Juli: 'July',
  August: 'August',
  September: 'September',
  Oktober: 'October',
  November: 'November',
  Dezember: 'December'
};

let month = str.split(' ')[0];
console.log(new Date(str.replace(month, months[month])));

// I am leaving timezone handling to you. Put some effort
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment-with-locales.min.js"></script>