码迷,mamicode.com
首页 > Web开发 > 详细

js获取n分钟(或n小时或n个月)后(或前)的时间(日期)

时间:2018-03-27 21:02:24      阅读:685      评论:0      收藏:0      [点我收藏+]

标签:second   asc   console   seconds   format   post   当前时间   var   格式   

  标题有点绕,其实意思就是根据系统当前时间,获取n分钟或n小时或n个月后的时间。

  例如:当前时间下,获取10分钟后的时间。

var date=new Date();     //1. js获取当前时间
var min=date.getMinutes();  //2. 获取当前分钟
date.setMinutes(min+10);  //3. 设置当前时间+10分钟:把当前分钟数+10后的值重新设置为date对象的分钟数
var y = date.getFullYear();
var m = (date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : (date.getMonth() + 1);
var d = date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate();
var h = date.getHours() < 10 ? (‘0‘ + date.getHours()) : date.getHours()
var f = date.getMinutes() < 10 ? (‘0‘ + date.getMinutes()) : date.getMinutes()
var s = date.getSeconds() < 10 ? (‘0‘ + date.getseconds()) : date.getSeconds()
var formatdate = y+‘-‘+m+‘-‘+d + " " + h + ":" + f + ":" + s;
console.log(formatdate) // 获取10分钟后的时间,格式为yyyy-mm-dd h:f:s

  同理,设置30分钟,60分钟或1个小时,5个小时,可以将小时转换为分钟,然后获取当前分钟再加上需要设置的时间即可。

 

  获取1个月后的日期:

var date=new Date();
date.setMonth(date.getMonth()+1);
var y = date.getFullYear();
var m = (date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : (date.getMonth() + 1);
var d = date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate();
var h = date.getHours() < 10 ? (‘0‘ + date.getHours()) : date.getHours()
var f = date.getMinutes() < 10 ? (‘0‘ + date.getMinutes()) : date.getMinutes()
var s = date.getSeconds() < 10 ? (‘0‘ + date.getseconds()) : date.getSeconds()
var formatwdate = y+‘-‘+m+‘-‘+d + " " + h + ":" + f + ":" + s; 
console.log(‘formatwdate‘, formatwdate)

  同理获取n个月后或n个月前的日期都是如此

js获取n分钟(或n小时或n个月)后(或前)的时间(日期)

标签:second   asc   console   seconds   format   post   当前时间   var   格式   

原文地址:https://www.cnblogs.com/jf-67/p/8659054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!