简体   繁体   中英

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

fromISO :

Create a DateTime from an ISO 8601 string

accepts ISO string, while you are passing a JavaScript Date.

You can use Date's toISOString() or luxon 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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