JS获取N年前/后,N月前/后,N日前/后并返回年月日时分秒日期格式

关于日期曾经闹过很多乌龙,刚入行时两个前端在那讨论什么什么时间不好实现,又是什么往前推N天,闰月怎么办等各种学术性问题,当然后来解决了,现在想想真的是脸红,JS里是有关于时间计算的原...

关于日期曾经闹过很多乌龙,刚入行时两个前端在那讨论什么什么时间不好实现,又是什么往前推N天,闰月怎么办等各种学术性问题,当然后来解决了,现在想想真的是脸红,JS里是有关于时间计算的原生函数的,可以完美实现向前或向后推N年,N月,N天,其实也很好实现,下面已经整理出JS的函数并可直接套用,使用时直接写在处理日期的函数里return一下即可,使用时直接调用,还可以使用传参动态拿时间。


向前推日期,当然用减号是向推前,用加号便是向后推了

获取向前推27天的日期 不用可不减27

// 获取向前推27天的日期 不用可不减27
let myDate = new Date(); //获取今天日期
let nowDate = new Date(myDate.setDate(myDate.getDate() - 27));
let year = nowDate.getFullYear();
let month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
let day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
let hour = nowDate.getHours() < 10 ? '0' + nowDate.getHours() : nowDate.getHours();
let minute = nowDate.getMinutes() < 10 ? '0' + nowDate.getMinutes() : nowDate.getMinutes();
let second = nowDate.getSeconds() < 10 ? '0' + nowDate.getSeconds() : nowDate.getSeconds();
let dateStr = year + "-" + month + "-" + day + ' ' + hour + ':' + minute + ':' + second;
console.log(dateStr)


获取向前推27个月的日期 不用可不减27

// 获取向前推27个月的日期 不用可不减27
let myDate = new Date(); //获取今天日期
let nowDate = new Date(myDate.setMonth(myDate.getMonth() - 27));
let year = nowDate.getFullYear();
let month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
let day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
let hour = nowDate.getHours() < 10 ? '0' + nowDate.getHours() : nowDate.getHours();
let minute = nowDate.getMinutes() < 10 ? '0' + nowDate.getMinutes() : nowDate.getMinutes();
let second = nowDate.getSeconds() < 10 ? '0' + nowDate.getSeconds() : nowDate.getSeconds();
let dateStr = year + "-" + month + "-" + day + ' ' + hour + ':' + minute + ':' + second;
console.log(dateStr)


// 获取向前推27年的日期  不用可不减27

// 获取向前推27年的日期  不用可不减27
let myDate = new Date(); //获取今天日期
let nowDate = new Date(myDate.setFullYear(myDate.getFullYear() - 27));
let year = nowDate.getFullYear();
let month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
let day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
let hour = nowDate.getHours() < 10 ? '0' + nowDate.getHours() : nowDate.getHours();
let minute = nowDate.getMinutes() < 10 ? '0' + nowDate.getMinutes() : nowDate.getMinutes();
let second = nowDate.getSeconds() < 10 ? '0' + nowDate.getSeconds() : nowDate.getSeconds();
let dateStr = year + "-" + month + "-" + day + ' ' + hour + ':' + minute + ':' + second;
console.log(dateStr)


以上便是JS获取N年前/后,N月前/后,N日前/后并返回年月日时分秒日期格式的所有内容

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
admin
admin

651 篇文章

作家榜 »

  1. admin 651 文章
  2. 粪斗 185 文章
  3. 王凯 92 文章
  4. 廖雪 78 文章
  5. 牟雪峰 12 文章
  6. 李沁雪 9 文章
  7. 全易 2 文章
  8. Stevengring 0 文章