失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > JavaScript 获取当前时间的前后几天 增加或减少指定天数

JavaScript 获取当前时间的前后几天 增加或减少指定天数

时间:2023-05-20 16:21:30

相关推荐

JavaScript 获取当前时间的前后几天 增加或减少指定天数

项目中需要对时间选择做出限制,只能选择当前日期前后几天

发现有问题,当月底时直接在getDate()函数加一天 会出现月底多一天的尴尬

出现问题

如当前时间:-03-31

var now = new Date();//创建时间对象

var today = now.getDate();//当天日期

var tomo = now.getDate()+1;//当天的后一天 日期

console.log(today);//31

console.log(tomo);//32

!!由此可见不能直接在getDate()后直接加一天

解决办法:

//用时间戳转日期

var now=newDate();

now=new Date(now.getTime());//时间戳转日期

var today = now.getDate();//当天日期

var tomo =newDate(now.getTime()+86400000*1);//当天的后一天

var tomoday = tomo.getDate();//当前的后一天 日期

console.log(today);//31

console.log(tomoday);//1

举一反三:

当前时间前一天:

var now=newDate();

now=new Date(now.getTime());//时间戳转日期

var today = now.getDate();//当天日期

var yes =newDate(now.getTime()-86400000*1);//当天的前一天

var yesterday = yes.getDate();//当前的前一天 日期

console.log(today);//31

console.log(yesterday);//30

封装函数:

/*

* Str string before/after 向前或向后推算

* Length int 向前后向后的天数

*/

function get_youwant_date(Str,Length){

var now=newDate();//创建时间对象

if(Str == 'before'){

var tomo=newDate(now.getTime()-86400000 * Length);//向前指定天数

}else{

var tomo=newDate(now.getTime()+ 86400000 * Length);//向后指定天数

}

varyear =now.getFullYear(),month=(now.getMonth()+1).toString(), day =now.getDate().toString();

//月份不足两位 补0

if(month.length==1){

month='0'+month;

}

//日期不足两位 补0

if(day.length==1){

day='0'+day;

}

varnewdate =(year+'-'+month+'-'+day);//输出指定日期格式

return newdate;

}

解决了项目中出现的问题,若对你有所帮助,那就更好了

如果觉得《JavaScript 获取当前时间的前后几天 增加或减少指定天数》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。