问题描述
我正在尝试找出 dayjs 中的 setter。为此,我测试了以下代码:
let orwell = dayjs();
orwell.year(1984);
console.log(orwell.format("YYYY"));
我的期望是 1984 年会出现在控制台中。但事实并非如此,而是出现了 2021 年。
我做错了什么?
解决方法
Dayjs 日期与时刻日期不同不可变。这意味着 dayjs 的任何实例都无法更改。年份设置器(或任何与此相关的方法)不会修改它被调用的实例,而是返回一个新的 dayjs 对象。
试试这个:
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
,
我认为我无法更改 'dayjs' 的对象。
但是,很容易将一个值作为字符串导入到 'dayjs()' 函数中。
useEffect(() => {
let orwell = dayjs('1984').format('YYYY-MM-DD HH:mm');
console.log('!!',orwell);
},[]);