When I try to create Date object from string format in Luxon I get invalid date.
Hours and minutes are not passed. This gives me an Invalid date
const dateString = '28.09.2022'; DateTime.fromFormat(dateString, 'dd.LL.yyyy HH:mm').toJSDate(); // Invalid date
Using moment library it seems that if hours and minutes are not passed it defaults to 00:00:00
const dateString = '28.09.2022'; moment(date, 'DD.MM.YYYY HH:mm').toDate(); // Wed Sep 28 2022 00:00:00 GMT+1000 (Australian Eastern Standard Time)
Is there some option to format both formats with hours and without in Luxon using one method as I was using moment in many places and it accepted ‘DD.MM.YYYY HH:mm’ format no matter if you pass HH:mm in string?
Advertisement
Answer
No, I fear that there is no native way to get moment(String, String)
behaviour in Luxon. Moreover, it seems that there is no counterpart of moment(String, String[])
in Luxon.
Please note that, while “Moment’s parser is very forgiving”, Luxon Parsing section of the docs states that “Luxon is quite strict about the format matching the string exactly.”
You can build your own custom method and implement the business logic you need, here a possible example:
const DateTime = luxon.DateTime; const customParse = (dateString) => { let dt = DateTime.fromFormat(dateString, 'dd.LL.yyyy'); if (dt.isValid) { return dt; } return DateTime.fromFormat(dateString, 'dd.LL.yyyy HH:mm'); } let dateString = '28.09.2022'; console.log(customParse(dateString).toJSDate()); dateString = '28.09.2022 11:46'; console.log(customParse(dateString).toJSDate());
<script src="https://cdn.jsdelivr.net/npm/luxon@3.0.4/build/global/luxon.min.js"></script>