Is it expected that dt.set()
will never return invalid dates?
#1705
-
For example: const today = DateTime.now().startOf("day");
let dt = DateTime.fromISO("2004-02-29");
let next = dt.set({ year: today.year });
console.log(next.isValid); -- returns true and value is 2025-02-28
next = dt.set({ year: 2028 });
console.log(next.isValid); -- returns true and value is 2028-02-29 i.e. in the first invocation it didn't generate 2025-02-29 which would be an invalid date. It seems some fallback was applied internally. Is this expected or am I relying on some undocumented bug/behaviour of Luxon by taking advantage of this behaviour? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
This is expected, invalid dates are only produced if the values you're providing are completely invalid. |
Beta Was this translation helpful? Give feedback.
-
Thanks for the report. You're right that a fallback is used internally to preserve validity (changing the date from 29 to 28 for non-leap years). That is expected behavior and you can take advantage of it safely. That being said, I can see why it might feel strange and unintuitive that
|
Beta Was this translation helpful? Give feedback.
This is expected, invalid dates are only produced if the values you're providing are completely invalid.
For "day of the month" specifically Luxon will clamp it to the valid month range, if you're not the one setting it, as in your example.
In general,
set
andfromObject
will behave likeDate.UTC
in that units that are out of range will overflow to the others.