js获得当前时间前后n天、n月、n年日期的一个简单实现

今天无意间看到自己曾经写过的一个javascript获取日期时间的小工具函数,作用是根据传入的时间单位参数(timeUnit,取值"d"、"M"、"y"分别表示天,月,年)与间隔n(n取负数表示n天/月/年前),获得n天、或n个月、或n年前/后的日期时间。

以下是代码:

function initDefaultDate(n,timeUnit) {
    var curr_date = new Date();
    if (timeUnit === 'd') {
    curr_date.setDate(curr_date.getDate() + n);
    } else if (timeUnit === 'M') {
        curr_date.setMonth(curr_date.getMonth() + n);
    } else if (timeUnit === 'y') {
        curr_date.setFullYear(curr_date.getFullYear() + n);
    }
    var strYear = curr_date.getFullYear();
    var strMonth = curr_date.getMonth()+1;
    var strDay = curr_date.getDate();
    var strHours = curr_date.getHours();
    var strMinutes = curr_date.getMinutes();

    var datastr = strYear + '-' + formatNumber(strMonth) + '-'
        + formatNumber(strDay) +' '+ formatNumber(strHours) + ':' + formatNumber(strMinutes);
    return datastr;
}
简易格式化显示日期的函数,作用为自动补0,如1=01。
function formatNumber(value){  
    return (value < 10 ? '0' : '') + value;  
}
代码很简单,实际使用中还是蛮方便的,例子如下:
initDefaultDate(-1,"d");    //获得当前时间1天前的日期
initDefaultDate(13,"M");    //获得当前时间13个月后的日期
initDefaultDate(14,"y");    //获得当前时间14年后的日期


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值