js对日期加减指定天、时、分、秒

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq395537505/article/details/78753237

在前端编程中,经常需要对日期进行加减天、时、分、秒的操作,例如使用JS实现日期的倒计时。类似于C#中的AddDays、AddHours等,下面介绍在js中对日期加减的方法。


例如:当前日期为 2016-12-11 20:20:20

 var t = new Date();//你已知的时间
 var t_s = t.getTime();//转化为时间戳毫秒数

 t.setTime(t_s + 1000 * 60);//设置新时间比旧时间多一分钟
 alert(t) // 2016-12-11 20:21:20

 t.setTime(t_s + 1000 * 60 * 60);//设置新时间比旧时间多一小时
 alert(t) // 2016-12-11 21:20:20

 t.setTime(t_s + 1000 * 60 * 60 * 24);//设置新时间比旧时间多一天
 alert(t) // 2016-12-12 20:20:20

var t = new Date();//你已知的时间

t.setTime(t.setMinutes(t.getMinutes() + 1));//设置新时间比旧时间多一分钟
alert(t) // 2016-12-11 20:21:20

t.setTime(t.setHours(t.getHours() + 1));//设置新时间比旧时间多一小时
alert(t) // 2016-12-11 21:20:20


猜你喜欢

转载自blog.csdn.net/qq395537505/article/details/78753237