2008-10-27 63 views
1

如何在JavaScript中實現下面的僞代碼?我想在第二個代碼摘錄中包含日期檢查,其中txtDate用於BilledDate。JavaScript中的日期解析和驗證

If ABS(billeddate – getdate) > 31 then yesno 「The date you have entered is more than a month from today, Are you sure the date is correct,」. 


if (txtDate && txtDate.value == "") 
{ 
    txtDate.focus(); 
    alert("Please enter a date in the 'Date' field.") 
    return false; 
} 

回答

1

一般來說,你在javascript日期對象的工作,而這些應與構建語法如下:

var myDate = new Date(yearno, monthno-1, dayno); 
    //you could put hour, minute, second and milliseconds in this too 

當心,爲期一個月的部分是索引,因此一月份爲0,二月是1,十二月份爲11 - )

然後你就可以拉出任何你想要的! .getTime()事物ret甕因爲Unix的時代開始的毫秒數,1970年1/1 00:00,SA這個值,你可以減去,然後看看如果該值大於你想要什麼:

//today (right now !-) can be constructed by an empty constructor 
var today = new Date(); 
var olddate = new Date(2008,9,2); 
var diff = today.getTime() - olddate.getTime(); 
var diffInDays = diff/(1000*60*60*24);//24 hours of 60 minutes of 60 second of 1000 milliseconds 

alert(diffInDays); 

這將返回一個小數數,所以可能你會想看看整數值:

alert(Math.floor(diffInDays)); 
-3

您好,美好的一天爲大家

你可以嘗試Refular表達式解析和驗證日期格式

這裏是一個URL同比增長可以看一些樣品,以及如何使用

http://www.javascriptkit.com/jsref/regexp.shtml

一個非常非常簡單的模式是:\ d {2}/\ d {2}/\ d {4}

爲MM/DD/YYYY或DD/MM/YYYY

由於沒有更多.... 再見

+0

不使用的字符串操作的數學 – StingyJack 2008-10-27 15:35:33

1

爲了獲得普通的JavaScript以天爲單位的時間差,你可以做這樣的:

var billeddate = Date.parse("2008/10/27"); 
var getdate = Date.parse("2008/09/25"); 

var differenceInDays = (billeddate - getdate)/(1000*60*60*24) 

但是,如果你想g等在你的日期處理更多的控制,我建議你使用最新的圖書館,我喜歡DateJS,這真的很好分析和操作在許多格式的日期,它是真正的語法糖:

// What date is next thrusday? 
Date.today().next().thursday(); 
//or 
Date.parse('next thursday'); 

// Add 3 days to Today 
Date.today().add(3).days(); 

// Is today Friday? 
Date.today().is().friday(); 

// Number fun 
(3).days().ago(); 
0

你可以用它來檢查有效日期

function IsDate(testValue) { 

     var returnValue = false; 
     var testDate; 
     try { 
      testDate = new Date(testValue); 
      if (!isNaN(testDate)) { 
       returnValue = true;    
      } 
      else { 
       returnValue = false; 
      } 
     } 
     catch (e) { 
      returnValue = false; 
     } 
     return returnValue; 
    } 

這就是你如何操縱JS日期。基本上,你創建的,現在(GETDATE)約會對象,增加31天,而其與輸入的日期

function IsMoreThan31Days(dateToTest) { 

    if(IsDate(futureDate)) { 
     var futureDateObj = new Date(); 
     var enteredDateObj = new Date(dateToTest); 

     futureDateObj.setDate(futureDateObj.getDate() + 31); //sets to 31 days from now. 
     //adds hours and minutes to dateToTest so that the test for 31 days is more accurate. 
     enteredDateObj.setHours(futureDateObj.getHours()); 
     enteredDateObj.setMinutes(futureDateObj.getMinutes() + 1); 

     if(enteredDateObj >= futureDateObj) { 
     return true; 
     } 
     else { 
     return false; 
     } 
    } 
}