js中 日期天数加1

来源:互联网 发布:美的面试 知乎 编辑:程序博客网 时间:2024/05/16 12:45

工作中经常会遇到当前日期+1或者+n的需求

举个例子:比如现在时间是2016-08-30, 需要显示的是30+1或者是30+n。+1是31号正常,+2呢?话说本尊不晓得哪个月份有32号哈?当然一年中也不会有13月

下面说一下我用的两种方法

第一种  通过本地字符串方法toLocaleString()得到最新时间

//获取当前时间,离开日期默认为t+1
function getLocalTime(addNum) {
var year,month,day,today,thatDay;
today = new Date().getTime();
thatDay = new Date( today + addNum*(24*60*60*1000) ).toLocaleString().substr(0,9);
year = thatDay.substr(0,4);
month = thatDay.substr(5,1);
day = thatDay.substr(7,2);
thatDay = year+"-"+month +"-"+day;
return thatDay
}
getLocalTime(2)
    获取当前日期的时间戳today ,时间戳是毫秒单位,所以需要将n转化成毫秒n*24860*60*1000。  
    简单说就是:当前时间戳(毫秒) + 需要增加的时间(毫秒) =  想得到的未来时间(毫秒);

    然后通过new Date(想得到的未来时间(毫秒))获取到加n之后的标准时间 如:  Wed Aug 04 2016 15:27:14 GMT+0800 (中国标准时间)
    再通过toLocaleString()方法转化成本地字符串  2016/8/4 下午3:28:11。
    最后通过截取和拼接字符串得到
    但是toLocaleString()方法有个坑,它存在浏览器兼容性的问题。
    问题描述:
    Date对象的toLocaleString方法在各个浏览器下的返回值存在格式上的差异。
    造成的影响:
    返回字符串的格式及长度不一致。
并且受影响的并非某个浏览器,而是所有浏览器,哦买噶的惊恐,不信?看下面测试情况
Chrome:Wed Aug 03 2016 15:58:48 GMT+0800 (中国标准时间)      toLocaleString 后: 2016/8/3 下午3:57:51
Firefox:Wed Aug 03 2016 16:03:05 GMT+0800                                     toLocaleString 后: 2016/8/3 下午4:03:05
Safari:Wed Aug 03 2016 16:06:37 GMT+0800 (Öйú±ê׼ʱ¼ä)    toLocaleString 后: Wednesday, August 03, 2016 16:06:37
可见这种方法在兼容性上是没有太大保障的,所以本尊立刻马上换了种方法

function getLocalTime(addNum){  var today,ms,thatDay, y, m, d,endDate;  today = new Date().getTime();  ms = today + addNum*24*60*60*1000;  thatDay = new Date(ms);  y = thatDay.getFullYear();  m = thatDay.getMonth()+1;  d = thatDay.getDate();  endDate = y+"-"+m+"-"+d;  return endDate}
getLocalTime(10)

所以通过getFullYear,getMonth,getDate的方法分别获取年月日这种方法还是比较好的,建议用此方法哈



0 0