一周前的日期(包含时分秒)

如果你需要计算一周前的日期,并且包含相同的时分秒,你可以将时分秒信息从当前时间中提取出来,然后将它们应用到一周前的日期上。

// 获取当前日期时间
const currentDate = new Date();

// 提取时分秒信息
const hours = currentDate.getHours();
const minutes = currentDate.getMinutes();
const seconds = currentDate.getSeconds();

// 计算一周前的日期
const oneWeekAgo = new Date(currentDate);
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);

// 应用相同的时分秒信息到一周前的日期
oneWeekAgo.setHours(hours);
oneWeekAgo.setMinutes(minutes);
oneWeekAgo.setSeconds(seconds);

// 格式化日期为 'yyyy-MM-dd HH:mm:ss' 格式
const oneWeekAgoFormatted = `${oneWeekAgo.getFullYear()}-${(oneWeekAgo.getMonth() + 1).toString().padStart(2, '0')}-${oneWeekAgo.getDate().toString().padStart(2, '0')} ${oneWeekAgo.getHours().toString().padStart(2, '0')}:${oneWeekAgo.getMinutes().toString().padStart(2, '0')}:${oneWeekAgo.getSeconds().toString().padStart(2, '0')}`;

console.log(oneWeekAgoFormatted); // 输出一周前的日期,包含时分秒


我们首先获取当前日期时间,并提取出当前时间的时分秒信息。然后,我们计算一周前的日期,并将相同的时分秒信息应用到这个日期上。最后,我们将结果格式化为 ‘yyyy-MM-dd HH:mm:ss’ 格式的字符串。

  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值