首页 > 其他 > 详细

获得前n天和后n天日期以及获得前n月和后n月的日期

时间:2018-06-15 18:57:30      阅读:203      评论:0      收藏:0      [点我收藏+]

提示:主要用到日期与时间戳的相互转换

一:获得前n天和后n天日期

  

技术分享图片
 1 countDays(2);   //+代表过去   -代表将来
 2 function countDays(day){
 3 
 4     var today=new Date();
 5     var milliseconds= today.getTime() - 1000 * 3600 * 24 * day;    //获得当前日期的时间戳(毫秒)进行计算
 6     var beforeday=new Date();
 7     beforeday.setTime(milliseconds);     //将毫秒转换为日期
 8      var strYear = defaultday.getFullYear();
 9     var strDay = defaultday.getDate();
10     var strMonth = defaultday.getMonth() + 1;
11     if (strMonth < 10) {
12         strMonth = "0" + strMonth;
13     }
14     if (strDay < 10) {
15         strDay = "0" + strDay;
16     }
17     alert(strYear + "-" + strMonth + "-" + strDay);    //将计算的时间赋值给defaultDate
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 }
View Code

 二:获得前n月和后n月日期

 

技术分享图片
 1 countMonths(2);     //+代表过去  -代表将来
 2 function countMonths(month){
 3     var today = new Date();
 4     var defaultmonth = new Date();
 5     defaultmonth.setMonth(today.getMonth()-month);   //用于设置月份
 6     var strYear = defaultmonth.getFullYear();
 7     var strMonth = defaultmonth.getMonth()+1;
 8     if (strMonth < 10) {
 9         strMonth = "0" + strMonth;
10     }
11 
12    alert(strYear + "-" + strMonth);
13  
14 }
View Code

 

获得前n天和后n天日期以及获得前n月和后n月的日期

原文:https://www.cnblogs.com/yuzihong/p/9188614.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!