Given two Date objects, how to properly set the month of the first object to the month of another?
I'm facing a task of copying day, month and year from one Date object to another. Copying day and year works as intended, the problem comes up when I'm trying to copy the month.
Using b.setMonth(a.getMonth())
results in b having its month one too many.
Using b.setMonth(a.getMonth() - 1)
however, results in b having its month one less than required.
The following typescript code:
let a = new Date(2018, 1, 12);
let b = new Date();
console.log(a);
console.log(b);
console.log('====');
console.log(a.getMonth());
console.log(b.getMonth());
b.setMonth(a.getMonth());
console.log('====');
console.log(a.getMonth());
console.log(b.getMonth());
b.setMonth(a.getMonth() - 1);
console.log('====');
console.log(a.getMonth());
console.log(b.getMonth());
Returns:
Mon Feb 12 2018 00:00:00 GMT+0100
Thu Aug 29 2019 16:11:03 GMT+0200
====
1
7
====
1
2
====
1
0 // 2 - 1 = 0 ?
Seemingly 2 - 1 should give 1 (a.getMonth() - 1)
, but apparently Date objects behave differently. What is the right way of copying month from one Date object to another in javascript/typescript? I suppose converting both dates to string, copying the right characters and parsing the string back to Date would work, but I'm wondering if there's an easier, more cleaner approach.
Date clone() method in Java with ExamplesThe clone() method of Date class in Java returns the duplicate of the passed Date object. This duplicate is just a shallow copy of the given Date object. Parameters: The method does not accept any parameters. Return Value: The method returns a clone of the object.
getSeconds() The getSeconds() method returns the seconds in the specified date according to local time.
It seems that much like in Java, dates in Javascript are mutable, meaning that it is possible to change a date after it has been created. We had this painfully shown to us when using the datejs library to manipulate some dates.
The problem is that the setMonth()
method has an optional second parameter which is the day (DOCS). If you don't provide a value for the day it will automatically use the one of the date.
So, your A date is 12 February 2018 while your B date is 29 August 2019.
By doing b.setMonth(a.getMonth());
you are implicitly saying b.setMonth(1,29);
(1 is a.getMonth() while 29 is the day form the b date).
So you are trying to set the date to the 29 February which isn't possible in 2019 and it shift the month by 1 to March (month 2).
If you do b.setMonth(a.getMonth() -1);
you are setting it to the 29 January, which is possible so you get January as a month (month 1).
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