码迷,mamicode.com
首页 > Web开发 > 详细

js 实现日期按月份加减

时间:2020-04-07 20:43:12      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:last   函数   get   class   pre   tail   tps   date   return   

 

let currentDate = "2019-04";
currentDate = new Date(currentDate); // 将日期格式转换为 Mon Apr 01 2019 08:00:00 GMT+0800 (中国标准时间)
 
// 月份加一
let lastDate = currentDate.setMonth(currentDate.getMonth() - 1); // 输出日期格式为毫秒形式1551398400000
 
lastDate = new Date(lastDate);
let lastYear = lastDate.getFullYear();
let lastMonth = checkMonth(lastDate.getMonth() + 1); // 因日期中的月份表示为0-11,所以要显示正确的月份,需要 + 1
 
lastDate = lastYear + ‘-‘ + lastMonth; // "2019-03"
 
 
// 月份减一
let nextDate = currentDate.setMonth(currentDate.getMonth() + 1); // 输出日期格式为毫秒形式1556668800000
 
nextDate = new Date(nextDate);
let nextYear = nextDate.getFullYear();
let nextMonth = checkMonth(nextDate.getMonth() + 1); // 因日期中的月份表示为0-11,所以要显示正确的月份,需要 + 1
 
nextDate = nextYear + ‘-‘ + nextMonth; // "2019-05"

 

其中,checkMonth 函数的作用是将单位数的月份前面加 ‘0’,比如:‘7’ 变成 ‘07’,代码如下所示:

 

checkMonth (i) {
    if (i<10){
        i="0" + i;
    }
    return i;
}

 

参考文档:https://blog.csdn.net/Dora_5537/article/details/89308860

 

js 实现日期按月份加减

标签:last   函数   get   class   pre   tail   tps   date   return   

原文地址:https://www.cnblogs.com/XUYIYUAN/p/12655432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!