Why is that I'm getting "Invalid DateTime" in the following Luxon/Moment code?
Asked Answered
A

2

6
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

Airhead answered 25/1, 2018 at 10:33 Comment(0)
G
17

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.

Gazetteer answered 25/1, 2018 at 10:39 Comment(0)
U
1

You can use fromJSDate like: luxon.DateTime.fromJSDate(new Date())

Unsnarl answered 14/10, 2019 at 3:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.