当前位置:   article > 正文

js获取当前日期的上个月的日期(不同的日期格式)_js根据当前年月日获取前一个月的年月日

js根据当前年月日获取前一个月的年月日
//处理日期格式
function formate(data, format) {
    data = new Date(data);
    var o = {
        "M+": data.getMonth() + 1, //月
        "d+": data.getDate(), //日
        "h+": data.getHours(), //时
        "m+": data.getMinutes(), //分
        "s+": data.getSeconds(), //秒
    }
    if(/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (data.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for(var k in o) {
        if(new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}
//获取当前日期的上个月日期
function getLastMonth(style = 'yyyy-MM'){
    let date = formate(new Date(),'yyyy/MM/dd');
    var arr = date.split('/');
    var year = arr[0]; //当前年
    var month = arr[1]; //当前月
    var day = arr[2]; //当前日
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前月的天数
    var year2 = year;
    var month2 = parseInt(month) - 1;
    if(month2 == 0) {
        year2 = parseInt(year2) - 1;
        month2 = 12;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if(day2 > days2) {
        day2 = days2;
    }
    if(month2 < 10) {
        month2 = '0' + month2;
    }
    var t2 = year2 + '/' + month2 + '/' + day2;
    let t3 = formate(t2,style);
    return t3;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

使用:

let d1 = getLastMonth('yyyy-MM-dd');
let d2 = getLastMonth('yyyy_MM--===dd');
console.log(d1)    //2020-02-29
console.log(d2)    //2020_02--===29
  • 1
  • 2
  • 3
  • 4

可以适用于正常(d1)及非正常(d2)的日期格式.
注:formate方法可以具体处理到时分秒的日期格式,但是获取当前日期的上一个月的日期是没有对时分秒进行处理的,只能具体到天,想要具体到时分秒的话,需要对getLastMonth这个方法进行修改。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/292381
推荐阅读
相关标签
  

闽ICP备14008679号