I have a date in this format "DD/MM/YYYY" and I want to convert it to a DateTime
object with Luxon library. How can I do it?
I know we can use methods like .fromISO()
, .fromHTTP()
, .fromSQL()
, .fromJSDate()
, and .fromFormat()
and none of them accepts the format I have, for example: "31/12/2022"
I was trying with fromFormat( date, 'D' )
but it's invalid because "D" format is equal to "MM/DD/YYYY".
You can use fromFormat
:
Create a DateTime from an input string and format string. Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see here.
passing "d/M/yyyy"
as second argument. Example:
const DateTime = luxon.DateTime;
console.log(DateTime.fromFormat("31/12/2022", "d/M/yyyy").toISO());
<script src="https://cdn.jsdelivr.net/npm/luxon@3.1.1/build/global/luxon.min.js"></script>
Please have a look at Parsing section of the docs and Table of tokens to see the list of available tokens. As docs states:
Note that many tokens supported by the formatter are not supported by the parser.
in your case "D" is a format token you can use standalone tokens to parse your input string.