JavaScript 中的日期解析和验证

2024-03-12

我如何在 JavaScript 中实现下面的伪代码?我想在第二个代码摘录中包含日期检查,其中 txtDate 代表 BilledDate。

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

一般来说,您在 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-age 开始以来的毫秒数,1/1 1970 00:00,你可以减去这个值,然后看看这个值是否大于你要:

//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));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaScript 中的日期解析和验证 的相关文章

随机推荐