moment / luxon

⏱ A library for working with dates and times in JS
https://moment.github.io/luxon
MIT License
15.23k stars 730 forks source link

JS: converting DateTime back to Date? #1463

Closed calicoder77 closed 11 months ago

calicoder77 commented 1 year ago

Good day,

I'm using Luxon to handle datetime tasks I need and great job devs, incredible project! Was wondering if it's possible to convert the DateTime I get back from DateTime.now().toFormat("ddhhmmLLLyy") back to a Date object? I see the toJSDate() function but is that usable with the other toFormat() command?

Appreciate any tips, thanks

diesieben07 commented 1 year ago

I am not 100% sure on what your question is. toFormat returns a string, formatted according to your format specification. If you want to turn this string back into a DateTime you can use parsing (DateTime.fromFormat and friends), however this process is lossy and I am not sure why you'd want to format a date only to immediately parse it again.

toJSDate returns a normal JavaScript Date object, which is mainly used when you need to interact with a third party library that requires a plain Date. Date has very primitive formatting and parsing capabilities, but again I am not sure why you'd want to use them if you're already using Luxon.

If you want both a formatted string and a plain JS date, just call toFormat and toJSDate on the same DateTime object. DateTime (like pretty much everything in Luxon) is immutable, so calling toFormat or toJSDate does not change the DateTime object:

const now = DateTime.now();
const formatted = now.toFormat("ddhhmmLLLyy"); // gives you a string
const jsDate = now.toJSDate(); // gives you a Date

Please let me know if this helps.