【发布时间】:2021-05-03 08:33:33
【问题描述】:
我正在开发一个 Angular 应用程序,尝试使用 momentJS 将特定年数添加到日期,但它似乎不起作用。
这是我的代码:
changeGuaranteeEndDate(guaranteeDuration) {
console.log("changeGuaranteeEndDate() START");
console.log("GUARANTEE START DATE: " + this.newAssetForm.value.guarantee_start_date);
console.log("GUARANTEE DURATION: " + this.newAssetForm.value.guarantee_duration);
console.log("EVENT VAL: " + guaranteeDuration);
this.newAssetForm.value.guarantee_duration = guaranteeDuration;
console.log("GUARANTEE DURATION: " + this.newAssetForm.value.guarantee_duration);
let myMoment: moment.Moment = moment(this.newAssetForm.value.guarantee_start_date);
console.log("myMoment: ", myMoment);
let myMoment2 = myMoment;
myMoment2.add(3, 'y')
console.log("myMoment2: ", myMoment2);
}
所以我基本上是从 this.newAssetForm.value.guarantee_start_date 中定义的日期开始创建 myMoment 对象。
然后我尝试从 myMoment 开始创建一个新的 myMoment2 对象,并且我将向该对象添加 3 年。终于打印出来了
问题是在 Chrome 控制台中我得到以下输出:
myMoment:
Moment {_isAMomentObject: true, _i: Fri Jan 29 2021 13:04:29 GMT+0100 (Ora standard dell’Europa centrale), _isUTC: false, _pf: {…}, _locale: Locale, …}
_d: Mon Jan 29 2024 13:04:29 GMT+0100 (Ora standard dell’Europa centrale) {}
_i: Fri Jan 29 2021 13:04:29 GMT+0100 (Ora standard dell’Europa centrale) {}
_isAMomentObject: true
_isUTC: false
_isValid: true
_locale: Locale {_calendar: {…}, _longDateFormat: {…}, _invalidDate: "Invalid date", _dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: ƒ, …}
_pf: {empty: false, unusedTokens: Array(0), unusedInput: Array(0), overflow: -2, charsLeftOver: 0, …}
__proto__: Object
myMoment2:
Moment {_isAMomentObject: true, _i: Fri Jan 29 2021 13:04:29 GMT+0100 (Ora standard dell’Europa centrale), _isUTC: false, _pf: {…}, _locale: Locale, …}
_d: Mon Jan 29 2024 13:04:29 GMT+0100 (Ora standard dell’Europa centrale) {}
_i: Fri Jan 29 2021 13:04:29 GMT+0100 (Ora standard dell’Europa centrale) {}
_isAMomentObject: true
_isUTC: false
_isValid: true
_locale: Locale {_calendar: {…}, _longDateFormat: {…}, _invalidDate: "Invalid date", _dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: ƒ, …}
_pf: {empty: false, unusedTokens: Array(0), unusedInput: Array(0), overflow: -2, charsLeftOver: 0, …}
__proto__: Object
问题在于,正如您在之前的输出中看到的那样,似乎年份没有添加到原始myMoment 对象中。
我的代码有什么问题?我错过了什么?如何正确地将年份添加到我的原始 myMoment 对象?
【问题讨论】:
-
你试过
console.log( this.newAssetForm.value.guarantee_start_date )吗?它返回什么? -
我刚刚创建了一个具有几乎完全相同逻辑的代码笔,它在那里完美地工作:codepen.io/Gh05d/pen/rNWNyvy?editors=1111
-
我相信代码运行良好。唯一的问题是您正在创建矩对象的浅层副本。并且随着年份的增加,您会看到这两个变量都发生了变化。你可以做
let myMoment2 = myMoment.clone();然后做加法。你会看到区别。
标签: javascript angular momentjs angular-moment