gpt4 book ai didi

Javascript 如何使用非英语字符串创建日期

转载 作者:行者123 更新时间:2023-11-28 14:34:05 25 4
gpt4 key购买 nike

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

该字符串是德语。正如预期的那样,我收到错误“无效日期”,因为 JS 希望我输入英文。

我不想使用toLocaleString(),因为我正在尝试从不同的语言初始化日期。

最佳答案

您可以使用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>

关于Javascript 如何使用非英语字符串创建日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50358244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com