欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

获取当天日期,获取之前之后的日期,前后几个月、前后几天、几小时

程序员文章站 2022-05-27 08:30:49
1.获取今天的日期 function getTodayDate(symbol) { symbol = symbol || '-'; var nowDate = new Date(), year = nowDate.getFullYear(), month = nowDate.getMonth() + ......

 

1.获取今天的日期

     function getTodayDate(symbol) {
        symbol = symbol || '-';
        var nowDate = new Date(),
            year = nowDate.getFullYear(),
            month = nowDate.getMonth() + 1,
            day = nowDate.getDate();
        month = month < 10 ? '0' + month : month;
        day = day < 10 ? '0' + day : day;
        return year + symbol + month + symbol + day;
    }

    getTodayDate('-') ;

2.获取之前N月(n<0)或者之后N月(n>0)

function getAnyMonth(symbol,n) {


  symbol = symbol||'-';
  var nowDate = new Date();
  nowDate.setMonth(nowDate.getMonth()+n);
  var year = nowDate.getFullYear(),
      month = nowDate.getMonth()+1;
  month = month < 10 ? '0' + month : month;
  return year + symbol + month;
}

//获取现在之前两个月:
getAnyMonth('', -2);

3.获取之前N天(n<0)或者之后N天(n>0)

    function getAnyDay(symbol, n) {
        symbol = symbol || '-';
        var nowDate = new Date();
        nowDate = nowDate.setDate(nowDate.getDate() + n);
        nowDate = new Date(nowDate);

        var y = nowDate.getFullYear(),
            m = nowDate.getMonth() + 1,
            d = nowDate.getDate();
        m = m < 10 ? '0' + m : m;
        d = d < 10 ? '0' + d : d;
        return y + symbol + m + symbol + d;
    }

    //获取现在之前5天:
    getAnyDay('-', -5);

4. 获取之前N小时(n<0)或者之后N小时(n>0)

    function getAnyHour(symbol, n) {
        symbol = symbol || '-';
        var nowDate = new Date();
        nowDate = nowDate.setHours(nowDate.getHours() + n);
        nowDate = new Date(nowDate);
        var y = nowDate.getFullYear(),
            m = nowDate.getMonth() + 1,
            d = nowDate.getDate(),
            h = nowDate.getHours(),
            mi = nowDate.getMinutes();
        m = m < 10 ? '0' + m : m;
        d = d < 10 ? '0' + d : d;
        h = h < 10 ? '0' + h : h;
        mi = mi < 10 ? '0' + mi : mi;
        return y + symbol + m + symbol + d + ' ' + h + ':' + mi;
    }

    //获取现在之前5小时:
    getAnyHour('-', -5);