JavaScript中的日期解析和验证
如何用JavaScript实现下面的伪代码?我想在第二段代码摘录中包含日期检查,其中txtDate是用于biledDate的JavaScript中的日期解析和验证,javascript,Javascript,如何用JavaScript实现下面的伪代码?我想在第二段代码摘录中包含日期检查,其中txtDate是用于biledDate的 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 ==
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;
}
大家好,大家好 您可以尝试使用Refular表达式来解析和验证日期格式 这里是一个网址,你可以看一些例子和如何使用 一个非常简单的模式是:\d{2}/\d{2}/\d{4} 适用于年月日或年月日 没有了。。。。
再见一般来说,您使用javascript中的日期对象,这些对象应使用以下语法构造:
var myDate = new Date(yearno, monthno-1, dayno);
//you could put hour, minute, second and milliseconds in this too
注意,月份部分是一个指数,所以一月是0,二月是1,十二月是11!)
然后您可以提取任何需要的内容,.getTime()返回自Unix时代开始以来的毫秒数,1/1 1970 00:00,så您可以减去该值,然后查看该值是否大于您想要的值:
//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));
要在纯JavaScript中获得以天为单位的日期差,可以这样做:
var billeddate = Date.parse("2008/10/27");
var getdate = Date.parse("2008/09/25");
var differenceInDays = (billeddate - getdate)/(1000*60*60*24)
但是,如果您想在日期操作中获得更多的控制权,我建议您使用日期库,我喜欢,以多种格式解析和操作日期非常好,而且它非常有语法优势:
// 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();
您可以使用此选项检查有效日期
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日期的方法。您基本上创建了一个日期对象now(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;
}
}
}
不要对Math使用字符串操作。我正在尝试验证格式正确的日期的值。