[英]How to convert localized date string to date object using moment
Using moment how can we convert localized date string to javascript date object?使用 moment 我们如何将本地化的日期字符串转换为 javascript 日期对象? Followed below steps, but got Current Output(check below).
遵循以下步骤,但得到了电流输出(检查下面)。
How can we get Expected Output?我们如何获得预期输出?
Could you please help me.请你帮助我好吗。
Ex: Setting moment locale as 'fr'
例如:将时刻语言环境设置为
'fr'
moment.defineLocale('fr', [localeObject][1]);
Now we get the date string as "27 févr. 2020 18:23:50"现在我们得到的日期字符串为“27 févr. 2020 18:23:50”
How can we convert it as dateobject?我们如何将其转换为日期对象?
moment("27 févr. 2020 18:23:50")
Expected output:预期输出:
Thu Feb 27 2020 18:23:50 GMT+0530 (India Standard Time)
2020 年 2 月 27 日星期四 18:23:50 GMT+0530(印度标准时间)
Current Output:电流输出:
Invalid Date
失效日期
You are getting Invalid Date because "27 févr. 2020 18:23:50"
is not in ISO 8601 nor in RFC 2822 compliant form, so you have to use moment(String, String)
.您收到无效日期,因为
"27 févr. 2020 18:23:50"
既不在 ISO 8601 中,也不在符合 RFC 2822 的格式中,因此您必须使用moment(String, String)
。 Moreover you have to use french locale, see i18n section of the doc.此外,您必须使用法语语言环境,请参阅文档的i18n部分。
As described in the docs , you can use DD
for days of the month, MMM
for month name (locale aware), YYYY
for 4 digit year, HH
for 0-23 hours (lowercase hh
for 1-12 hours), mm
for minutes and ss
for seconds.如文档中所述,您可以使用
DD
表示月份中的天数, MMM
表示月份名称(区域设置), YYYY
表示 4 位数字年份, HH
表示 0-23 小时(小写hh
表示 1-12 小时), mm
表示分钟和ss
几秒钟。
Then you can use toDate()
to get a JavaScript date from a moment object:然后您可以使用
toDate()
从 moment 对象获取 JavaScript 日期:
To get a copy of the native Date object that Moment.js wraps, use
moment#toDate
.要获取 Moment.js 包装的本机 Date 对象的副本,请使用
moment#toDate
。
Snippet with working code sample:带有工作代码示例的片段:
console.log( moment("27 févr. 2020 18:23:50", "DD MMM YYYY HH:mm:ss").toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/locale/fr.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.