0

I am trying to figure out setters in dayjs. To that extent, I tested out the following code:

let orwell = dayjs();
orwell.year(1984);
console.log(orwell.format("YYYY"));

My expectation is that the year 1984 will show up in the console. But that is not the case, instead 2021 shows up.

What am I doing wrong?

Moshe
  • 6,011
  • 16
  • 60
  • 112

2 Answers2

1

Dayjs dates unlike moment dates are immutable. That means that any instance of a dayjs cannot ever ever be changed. The year setter (or any method for that matter) does not modify the instance it is being called on but returns a new dayjs object instead.

Try this:

let now = dayjs();
let orwell = now.year(1984);
console.log(orwell.format("YYYY")); // should print 1984
console.log(now.format("YYYY"));    // should print the current year
icguy
  • 560
  • 4
  • 14
0

I don't think I can change the object of 'dayjs'.

However, it is easy to import a value into the 'dayjs()' function as a string.


useEffect(() => {
    let orwell = dayjs('1984').format('YYYY-MM-DD HH:mm');
    console.log('!!', orwell);
  }, []);
imer
  • 55
  • 5