简体   繁体   English

为什么我在下面的 Luxon/Moment 代码中得到“Invalid DateTime”?

[英]Why is that I'm getting "Invalid DateTime" in the following Luxon/Moment code?

const dt = DateTime.fromISO(new Date(date))
// dt => DateTime {ts: 1516876197386, zone: LocalZone, loc: Locale, invalid: "unparsable", weekData: null, …}
return dt.toFormat('yyyy/mm/dd')

The result is: Invalid DateTime .结果是: Invalid DateTime Why is this and how to fix it?为什么会这样以及如何解决?

Luxon's docs: https://moment.github.io/luxon/docs/class/src/datetime.js~DateTime.html#instance-method-toFormat Luxon 的文档: https ://moment.github.io/luxon/docs/class/src/datetime.js~DateTime.html#instance-method-toFormat

fromISO : fromISO

Create a DateTime from an ISO 8601 string 从ISO 8601字符串创建DateTime

accepts ISO string, while you are passing a JavaScript Date. 在传递JavaScript日期时接受ISO字符串。

You can use Date's toISOString() or luxon fromJSDate 您可以使用Date的toISOString()或JSDate中的fromJSDate

 const DateTime = luxon.DateTime; const dt = DateTime.fromISO(new Date().toISOString()); console.log(dt.toFormat('yyyy/MM/dd')); const dt2 = DateTime.fromJSDate(new Date()); console.log(dt2.toFormat('yyyy/MM/dd')); 
 <script src="https://moment.github.io/luxon/global/luxon.min.js"></script> 

Moreover, note that you have to use uppercase MM to print month instead of lowercase mm that stands for minutes. 此外,请注意,必须使用大写的MM打印月份,而不要使用代表分钟的小写mm

您可以像这样使用 fromJSDate: luxon.DateTime.fromJSDate(new Date())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM