首页 > 代码库 > js计算输入日期的前一天,后一天(上一日,下一日)。兼容safari
js计算输入日期的前一天,后一天(上一日,下一日)。兼容safari
//下一天
function getNextday(){
var today=document.getElementById("lang0").value;
var t=new Date(today);
var tm=new Date(t.getFullYear(),t.getMonth(),t.getDate()+1);
var m=‘0‘+(tm.getMonth()+1);
var d=‘0‘+tm.getDate()
document.getElementById("lang0").value= http://www.mamicode.com/tm.getFullYear()+‘-‘+m.substr(m.length-2)+‘-‘+d.substr(d.length-2);
}
//前一天
function getYestoday(date){
var date=document.getElementById("lang0").value;
var t=new Date(date);
var yesterday_milliseconds=t.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}
datastr = strYear+"-"+strMonth+"-"+strDay;
document.getElementById("lang0").value=http://www.mamicode.com/datastr;
}
以上在Firefox和Chrome上都没有问题,但在safari上出错,找了一下原因,是需要将string的日期转换一下,如下:
//下一天
function getNextday(){
var today=document.getElementById("lang0").value;
var t = new Date(Date.parse(today.replace(/-/g, "/")));
var tm=new Date(t.getFullYear(),t.getMonth(),t.getDate()+1);
var m=‘0‘+(tm.getMonth()+1);
var d=‘0‘+tm.getDate()
document.getElementById("lang0").value= http://www.mamicode.com/tm.getFullYear()+‘-‘+m.substr(m.length-2)+‘-‘+d.substr(d.length-2);
}
//前一天
function getYestoday(date){
var date=document.getElementById("lang0").value;
var t = new Date(Date.parse(date.replace(/-/g, "/")));
var yesterday_milliseconds=t.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}
datastr = strYear+"-"+strMonth+"-"+strDay;
document.getElementById("lang0").value=http://www.mamicode.com/datastr;
}
js计算输入日期的前一天,后一天(上一日,下一日)。兼容safari