0

I want to store two values in an object: today, todayInOneYear. I use a function to calculate the +1 year.

obj = {}
today = new Date();

obj = {
  today: today,
  oneYear: addOneYear(today)
}
console.log(obj)

function addOneYear(date) {
  date.setFullYear(date.getFullYear() + 1);
  return date;
}

Problem: Today and todayInOneYear are the same. But I expect two different dates. Once from now (today) and then once from a year from now. Do you know what I'm missing?

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
  • 1
    I'm confused: if *"Today and todayInOneYear are the same. I am not aware that I made a deep copy"* then why *"therefore I expect two different dates"*? – Gerardo Furtado Nov 07 '22 at 12:44
  • 1
    _“I am not aware that I made a deep copy. Therefore I expect two different dates.”_ — Huh? Did you mean the opposite of that statement? You need to clone the Date, resulting in two objects instead of one, if you want two different dates. See [How to clone a Date object?](/q/1090815/4642212) and [Modifying a copy of a JavaScript object is causing the original object to change](/q/29050004/4642212). – Sebastian Simon Nov 07 '22 at 12:44
  • @SebastianSimon You are right. Sorry for my english. I updated my question. Thank you and Gerado for the hint. – Maik Lowrey Nov 07 '22 at 12:48

2 Answers2

2

You'll need to clone the Date object:

obj = {}
today = new Date();

obj = {
  today: today,
  oneYear: addOneYear(today)
}
console.log(obj)

function addOneYear(date) {
  let clone = new Date(date);
  clone.setFullYear(clone.getFullYear() + 1);
  return clone;
}
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    While this is true, this can’t be the answer to the _real_ question, can it? Otherwise this would just need to be closed as a duplicate of [How to clone a Date object?](/q/1090815/4642212)… – Sebastian Simon Nov 07 '22 at 12:49
  • One more question: why i will get a timestamp when i return directly `return clone.setFullYear(clone.getFullYear() + 1);` – Maik Lowrey Nov 07 '22 at 13:09
  • 1
    @MaikLowrey That’s what [`setFullYear`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear) returns. – Sebastian Simon Nov 07 '22 at 13:17
  • yes sorry i mean it returns a unix timestamp – Maik Lowrey Nov 07 '22 at 13:21
0

You can try this code

obj = {}
today = new Date();

obj = {
  today: today,
  oneYear: addOneYear(today)
}
console.log(obj)
function addOneYear(date) {
  const aYearFromNow = new Date(date);
  aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 1);
    console.log(aYearFromNow)
  return aYearFromNow;
}