javascript - 将今天的日期分配给键并引用此键以添加 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])
}
解决方案
您应该意识到调整 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);
推荐阅读
- vbscript - 如何在vbscript中将数字转换为前面有零的字符串?
- css - 方法在角度材料自动完成中被多次调用
- python-3.x - 为什么带有 autorun script.py 的 mqtt 无法稳定与 broker 的连接?
- mongodb - 使用 Homebrew 安装 MongoDB
- css - dompdf pdf的背景被剪掉了
- wordpress - 当我对我的站点执行 GTMetrix 测试时,它显示以下内容。我怎样才能解决这个问题?
- mongodb - Heroku MongoSocketReadException:过早到达流的末尾
- python - 如何使用“cross_val_predict”方法在一行中获得预测概率和预测标签以进行多类预测?
- javascript - Firebase 数据库没有响应
- sql - 从具有多个条件的 1 个表中选择行