Javascript 如何使用javascript将文本框中输入的日期与当前日期进行比较?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11719202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:49:54  来源:igfitidea点击:

how to compare the date entered in textbox to the current date using javascript?

javascript

提问by akhil

How can I check that the date entered in a textbox is less than today's date using java script?

如何使用java脚本检查文本框中输入的日期是否小于今天的日期?

I m using code

我正在使用代码

var currentDate_Month = new Date().valueOf().getMonth();
        var currentDate_Date = new Date().getDate();
        var currentDate_Year = new Date().getFullYear();
        var EnterDate_Month = new Date(document.getElementById('ctl00_ContentPlaceHolder1_txtDateReceived').value).getMonth();
        var EnterDate_Date = new Date(document.getElementById('ctl00_ContentPlaceHolder1_txtDateReceived').value).getDate();
        var EnterDate_Year = new Date(document.getElementById('ctl00_ContentPlaceHolder1_txtDateReceived').value).getFullYear();

        if(EnterDate_Year<currentDate_Year) {
          if(EnterDate_Month<currentDate_Month) {
            if(EnterDate_Date<currentDate_Date) {
            }
           }
          }
         else {   
            str += '</br>* Date should be Less than or equals to current Date.';
            return false;
         }

But to my surprise the current date coming in the textbox control is Sat Jun 7 2014 when viewing it by -

但令我惊讶的是,当通过以下方式查看时,文本框控件中的当前日期是 2014 年 6 月 7 日星期六 -

new Date(document.getElementById('ctl00_ContentPlaceHolder1_txtDateReceived').value).toDateString();

Why is it returning the date in this format? (the date in text box is in format dd/mm/yyyy)

为什么它以这种格式返回日期?(文本框中的日期格式为 dd/mm/yyyy)

thanks in advance.

提前致谢。

回答by svanryckeghem

You could simplify your code:

你可以简化你的代码:

var today = new Date();

var enterDate = new Date(Date.Parse(document.getElementById('ctl00_ContentPlaceHolder1_txtDateReceived')));

if (enterDate.valueOf() < today.valueOf())
{
    // To what you have to do...
}

回答by Jacob George

A Date() can be initialized as

一个 Date() 可以被初始化为

Date("mm/dd/yyyy")

Since this is the adopted method, the format of dd/mm/yyyy is not possible. The best method in your case will be to do the following

由于这是采用的方法,因此无法使用 dd/mm/yyyy 格式。在您的情况下,最好的方法是执行以下操作

dateFields = (document.getElementById('ctl00_ContentPlaceHolder1_txtDateReceived').value.split('/')

date = Date(dateFields[2],dateFields[1]-1, dateFields[0])

This would be in the format

这将是格式

Date(year, month, date)

Then, you can compare the textbox date with the present date

然后,您可以将文本框日期与当前日期进行比较

date < Date.now()