Javascript : 将 Date 对象增加一年

Javascript : Increase a Date object by a year

我正在为我的对象属性分配一个新的日期对象:

giftObject.purshasedDate = 新日期()

给出日期格式:

Date Thu Feb 20 2020 13:36:37 GMT+0100 (heure normale d’Europe centrale)

我想将这个日期增加一年,我试过了:

new Date().setFullYear(giftObject.purshasedDate.getFullYear() + 1) 但它给出的序列号是这样的:1613824899244

我不明白那个序号是什么意思!这是约会还是应该尝试其他事情?

默认情况下,所有日期对象都是时间戳。

JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC. Source : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

我认为默认的 new Date() 对象可以将自身显示为字符串,实际上它也是一个时间戳。 如果要将日期显示为字符串,则必须在日期上使用 toLocaleString() 方法。

我尝试更新原始日期,它 return 日期的字符串,不知道为什么,但它通过更新原始日期工作。

示例:

let giftObject = {};
giftObject.purshasedDate = new Date();
giftObject.purshasedDate.setFullYear(giftObject.purshasedDate.getFullYear() + 1);
console.log(giftObject.purshasedDate)

结果:"20/02/2021 à 13:55:49" 我的法语浏览器

const oldDate = new Date("Date Thu Feb 20 2020 13:36:37 GMT+0100")
const newDate = oldDate.setFullYear(oldDate.getFullYear() + 1)
const dateWithPlusOneYear = new Date(newDate)
console.log(new Date(dateWithPlusOneYear))
//Sat Feb 20 2021 13:36:37 GMT+0100 (Central European Standard Time)

请使用这个:

    purshasedDate = new Date();
    purshasedDate = new Date(purshasedDate.setFullYear(purshasedDate.getFullYear() + 1));