使用 JavaScript 来获取当前日期的三个月前、半年前和一年前的时间;结果以 “yyyy-mm-dd”这种日期格式展示

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

// 获取三个月前的时间
const threeMonthsAgo = new Date();
threeMonthsAgo.setMonth(currentDate.getMonth() - 3);

// 获取半年前的时间
const sixMonthsAgo = new Date();
sixMonthsAgo.setMonth(currentDate.getMonth() - 6);

// 获取一年前的时间
const oneYearAgo = new Date();
oneYearAgo.setFullYear(currentDate.getFullYear() - 1);

// 将日期对象转换为自定义日期格式
const formatDateString = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

// 输出结果
console.log(formatDateString(threeMonthsAgo));
console.log(formatDateString(sixMonthsAgo));
console.log(formatDateString(oneYearAgo));

在上述代码中,currentDate 是当前日期对象,我们利用 setMonth()setFullYear() 方法来设置相应的月份和年份。我们定义了一个 formatDateString 函数,接受一个日期对象作为参数,并根据年份、月份和日期格式化成 "YYYY-MM-DD" 的格式。我们使用 getFullYear()getMonth()+1getDate() 方法获取相应日期的年份、月份和日期,并使用 String.prototype.padStart() 方法来确保月份和日期都是两位数字。

最后,我们可以通过 console.log() 输出符合我们需求的日期字符串。

请注意,JavaScript 中的日期对象是基于本地时区设置的。如果你希望在处理日期时使用的是其他时区,你需要使用相关的第三方库或手动进行时区转换。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值