Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating the date portion of a javascript object without changing the time portion

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?

like image 311
plusplusben Avatar asked Oct 05 '22 19:10

plusplusben


2 Answers

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.

like image 50
zachelrath Avatar answered Oct 10 '22 04:10

zachelrath


First set the date, then the month.

like image 31
MaxArt Avatar answered Oct 10 '22 03:10

MaxArt