首页 > 解决方案 > 将今天的日期分配给键并引用此键以添加 5 天

问题描述

我正在尝试将今天的日期分配给contVfrmDate并使用值/日期以 x 天数递增下一个键?可以在对象/字典中完成吗?如果是,如何?

const ccCustInfo = {
  cropConsultant: 'Test this',
  customerName:   'Customer',
  customerBranch: 'MULBERRY ',
  shippingAddress:'address',
  contractType:   'SKU',
  contVfrom:      'Contract Valid From',
  contVto:        'Contract Valid To',
  internalNotes:  'Internal Notes',
  contVfrmDate:    (new Date(Date.now()).toLocaleString().split(',')[0]),
  contVtoDate:     contVfrmDate.setDate(contVfrmDate.getDate() + 5)
}

在 Chrome 控制台中,我看到了这个错误。

Uncaught ReferenceError: contVfrmDate is not defined
at <anonymous>:11:24

找到另一个简单的解决方案,因为to date默认为 8 天。

contVtoDate: (new Date(Date.now() + (8 /*days*/ * 86400000 /*ms per day*/)).toLocaleString().split(',')[0])}

const ccCustInfo = {
          cropConsultant: 'Test this',
          customerName:   'Customer 5K FARMS',
          customerBranch: 'MULBERRY FL',
          shippingAddress:'3010',
          contractType:   'SKU',
          contVfrom:      'Contract Valid From',
          contVto:        'Contract Valid To',
          internalNotes:  'Internal Notes',
          contVfrmDate:    (new Date(Date.now()).toLocaleString().split(',')[0]),
          contVtoDate:     (new Date(Date.now() + (8 /*days*/ * 86400000 /*ms per day*/)).toLocaleString().split(',')[0])
}
       

标签: javascriptnode.jsjasminewebdriver-io

解决方案


您应该意识到调整 Date 对象.setDate()将更改原始日期。所以你需要两个独立的日期对象:

    const frmDate = new Date();
    const toDate = new Date();

但是toDate需要5天的时间。最直接的方法是现在使用.setDate()方法 on toDate。通过获取日期frmDate并添加您的 5 天来做到这一点:

toDate.setDate(frmDate.getDate() + 5);

结果如下所示:

const frmDate = new Date();
const toDate = new Date()
toDate.setDate(frmDate.getDate() + 5);

const ccCustInfo = {
  cropConsultant: 'Test this',
  customerName:   'Customer',
  customerBranch: 'MULBERRY ',
  shippingAddress:'address',
  contractType:   'SKU',
  contVfrom:      'Contract Valid From',
  contVto:        'Contract Valid To',
  internalNotes:  'Internal Notes',
  contVfrmDate:    frmDate.toLocaleString('en-US',{month: 'numeric', day: 'numeric', year: 'numeric'}),
  contVtoDate:     toDate.toLocaleString('en-US',{month: 'numeric', day: 'numeric', year: 'numeric'})
}
console.log(ccCustInfo);


推荐阅读