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= 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=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= 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=datastr;
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。