本文實例講述了JS獲取及驗證開始結束日期的方法。分享給大家供大家參考,具體如下:
function validation()
{
var startdate=document.getElementById("start_tenancyDate_s").value;
var enddate=document.getElementById("end_tenancyDate_s").value;
var datesent=dateDiff(enddate,startdate);
if(startdate=="")
{
alert("請選擇開始日期!");
return false;
}
if(enddate=="")
{
alert("請選擇結束日期!");
return false;
}
if(datesent>365)
{
alert("選擇的日期差超過最大值1年!");
return false;
}
if(datesent<0)
{
alert("選擇的日期有誤,結束日期必須大於開始日期!");
return false;
}
else{return true;}
}
//調用該方法(主方法)
function dateDiff(date1, date2){
var type1 = typeof date1, type2 = typeof date2;
if(type1 == 'string')
date1 = stringToTime(date1);
else if(date1.getTime)
date1 = date1.getTime();
if(type2 == 'string')
date2 = stringToTime(date2);
else if(date2.getTime)
date2 = date2.getTime();
return (date1 - date2) / (1000 * 60 * 60 * 24);//除1000是毫秒,不加是秒
}
//字符串轉成Time(dateDiff)所需方法
function stringToTime(string){
var f = string.split(' ', 2);
var d = (f[0] ? f[0] : '').split('-', 3);
var t = (f[1] ? f[1] : '').split(':', 3);
return (new Date(
parseInt(d[0], 10) || null,
(parseInt(d[1], 10) || 1)-1,
parseInt(d[2], 10) || null,
parseInt(t[0], 10) || null,
parseInt(t[1], 10) || null,
parseInt(t[2], 10) || null
)).getTime();
}
更多關於JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript時間與日期操作技巧總結》、《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。