将字符串转换为日期并更改该日期

Convert string to date and alter that date

美好的一天,我正在从一个字符串中生成 3 个日期,我希望输出是:

billing date: 2020/01/11
cutoff start: 2019/11/11
cuttof end: 2019/12/10

但我得到以下信息:

billing date: 2020/11/10
cutoff start: 2019/11/10
cuttof end: 2019/12/10

我想知道javascript如何使用变量或者问题是什么,因为一切都被改变了

var month = "Jan-20"
var coverage_month_obj = moment(month, 'MMM-YY').toDate();
var billing_date = new Date(coverage_month_obj.setDate(coverage_month_obj.getDate() + 10))
var cutoff_end = new Date(billing_date.setMonth(billing_date.getMonth() - 1))
cutoff_end = new Date(billing_date.setDate(billing_date.getDate() - 1))
var cutoff_start = new Date(billing_date.setMonth(billing_date.getMonth() - 1))

I would like to know how javascript works with variables or what is the problem since everything is altered

简单地说,在 javascript 日期变量上调用 setXXX 就地更新该变量 。也就是说,这就是我们所说的 "mutable"。您可能假设日期是不可变的并且不会原地更改。


为了更好地实现您的目标,我建议您使用 other functionality of momentjs 从给定的输入字符串中计算您的 3 个日期。

var month = "Jan-20"
var coverage_month = moment(month, 'MMM-YY');

//Jan-20 I need to convert it into date format and that the day is 11 (2020/01/11) cutoff start, are two months less from that date (2020/11/11) and cutoff end is one month less from Jan-20, but ends on day 10 (2020/12/10)

var billing_date = coverage_month.clone().add(10, 'days');
var cutoff_start = billing_date.clone().subtract(2, 'months');
var cutoff_end = billing_date.clone().subtract(1,'months').subtract(1,'day')

console.log("billing_date",billing_date);
console.log('cutoff_start',cutoff_start);
console.log('cutoff_end',cutoff_end);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>