2008-10-27 65 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; 
     } 
    } 
}