js脚本: 在文本框中输入一个日期值后按确定按钮后和当前时间比较大小

JavaScript09

js脚本: 在文本框中输入一个日期值后按确定按钮后和当前时间比较大小,第1张

function

check()

{

var

d

=

new

Date()

//取当前年月日,舍去时分秒

d

=

new

Date(d.getFullYear()

+

"-"

+

(d.getMonth()

+

1)

+

"-"

+

d.getDate())

var

d2

=

new

Date(document.

getElementById

("txtDate").value)

if

(d2

==

"Invalid

Date")

{

alert("非日期")

return

}

//getTime

从1970.1.1开始的毫秒数

var

n

=

d.getTime()

-

d2.getTime()

if

(n

==

0)

{

alert("相等")

}

else

if

(n

>

0)

{

alert("小于当前日期")

}

else

{

alert("大于当前日期")

}

}

具体的时间格式我用的是yyyy-MM-dd HH:mm:ss

//判断时间大小

function compareDate(d1,d2)

{

return ((new Date(d1.replace(/-/g,"\/"))) >(new Date(d2.replace(/-/g,"\/"))))

}

如果比较时间,一般都是将时间转换成相对应的毫秒数进行比较。

下面是个简单的例子,仅供参考:

<script>

    function compare(date1,date2){

        var oDate1 = new Date(date1)

        var oDate2 = new Date(date2)

        if(oDate1.getTime() > oDate2.getTime()){

            alert('第一个大')

        } else if (oDate1.getTime() < oDate2.getTime()){

            alert('第二个大')

        } else {

            alert('相等')

        }

        

    }

</script>