1、获取今天:
var today = new Date().toLocaleDateString().replace(/\//g, "-"); alert(today); //上述代码,当日小于10时,输出不带0的数字,比如今天是2017-01-01,输出2017-01-1,格式不太统一,可能在某些情况下会用起来不方便,改成如下: function getToday(){ var nowdate = new Date(); var y = nowdate.getFullYear(); var m = nowdate.getMonth()+1; var d = nowdate.getDate(); if(m<10) { m="0"+m; } if(d<10) { d="0"+d; } return y+'-'+m+'-'+d; } alert(getToday()); // 输出今日时间
2、获取指定时间的前一天:
//获取2017-01-01前一天,输出2016-12-31 alert(GetPrevDay('2017-01-01')); //获取指定时间的前一天 function GetPrevDay(str) { var year = str.substring(0,4); var month = str.substring(5,7); var day = str.substring(8,10); var today=new Date(year, month-1 ,day); var yesterday_milliseconds=today.getTime()-1000*60*60*24; var yesterday=new Date(); yesterday.setTime(yesterday_milliseconds); var strYear=yesterday.getFullYear(); var strDay=yesterday.getDate(); var strMonth=yesterday.getMonth()+1; if(strMonth<10) { strMonth="0"+strMonth; } if(strDay<10) { strDay="0"+strDay; } return strYear+"-"+strMonth+"-"+strDay; }
3、获取指定时间的后一天:
//获取2017-01-01前一天,输出2017-01-02 alert(getNextDay('2017-01-01')); //获取指定时间的后一天 function getNextDay(str){ str = new Date(str); str = +str + 1000*60*60*24; str = new Date(str); var y=str.getFullYear(); var m= str.getMonth()+1; var d= str.getDate() ; if(m<10) { m="0"+m; } if(d<10) { d="0"+d; } return y+'-'+m+'-'+d; }
4、获取今天的前一个月时间
//输出时间 alert(getPrevMonth()); //获取当前日期的前一个月时间 function getPrevMonth(){ var nowdate = new Date(); //获取系统前一个月的时间 nowdate.setMonth(nowdate.getMonth()-1); var y = nowdate.getFullYear(); var m = nowdate.getMonth()+1; var d = nowdate.getDate(); if(m<10) { m="0"+m; } if(d<10) { d="0"+d; } return y+'-'+m+'-'+d; }
5、获取今天的前一周时间
//输出时间 alert(getPrevWeek()); //获取当前时间的前一周时间 function getPrevWeek(){ var nowdate = new Date(); var oneweekdate = new Date(nowdate -7*24*3600*1000); var y = oneweekdate.getFullYear(); var m = oneweekdate.getMonth()+1; var d = oneweekdate.getDate(); if(m<10) { m="0"+m; } if(d<10) { d="0"+d; } return y+'-'+m+'-'+d; }