提示:主要用到日期与时间戳的相互转换
一:获得前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 }
二:获得前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 }
原文:https://www.cnblogs.com/yuzihong/p/9188614.html