What is the best way in JavaScript to set the date portion of a JavaScript date object without affecting the time portion?
Lets say you have a date like this
Wed Oct 31 2012 10:15:00 GMT-0400 (EDT)
And you want to update it to be November 1st without changing the time.
At first glance, you'd think this would work,
exampledate.setFullYear(2012);
exampledate.setMonth(10);
exampledate.setDate(1);
But the result is
Sat Dec 01 2012 10:15:00 GMT-0500 (EST)
I think reason for this is that October has 31 days and November has just 30. Since this obviously doesn't work right all the time. What are my other options? Will I have to create a new date object?
JavaScript Date object setter methods often allow you to (optionally) set multiple date/time components all at once (in addition to the primary component), as appropriate for the situation --- this is what you want to do.
For your use case, the syntax for setFullYear
is setFullYear(year,month,day)
, so in addition to explicitly setting the year (which would cause the month and date to be implicitly updated based on your initial date), you could also explicitly set the month and day while you're at it. For instance:
var d = new Date();
d.setFullYear(2020,10,3);
will return
Tue Nov 03 2020 13:10:34 GMT-0500 (EST)
See the JavaScript setFullYear() method for more details.
Because the time components of the Date object (e.g. hours, minutes, seconds, milliseconds) are not dependent on the date portions (year,month,date), your initial time components will be maintained. If you need to then update the time components, you can safely use setHours()
or other methods as needed, because no implicit updates to the date components will occur.
First set the date, then the month.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With