javascript比较两个日期并发出警报 [英] javascript compare two dates and throw an alert

查看:115
本文介绍了javascript比较两个日期并发出警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个日期在DD / MM / YYYY HH:MM:SS格式,我想比较两个日期,并抛出一个



警报。



我尝试了下面的代码,但它不起作用。

  startdate = 14/12/2014 19:00:00; 
enddate =21/01/2015 19:00:00;

if(new Date(startdate)> new Date(enddate))
{
alert(结束日期不能小于开始日期);

}


解决方案

使用以下构造函数创建一个日期:

  new Date(); 
new Date(value);
new Date(dateString);
new Date(year,month [,date [,hour [,minutes [,seconds [,milliseconds]]]]]);

您已经使用了其中的第三个,其中 dateString 是一个


表示日期的字符串值。字符串的格式应为DateParse()方法识别的格式
(符合IETF标准的RFC 2822
时间戳,也是ISO8601的版本)。




您提供的字符串格式不正确。因此,相应的日期对象尚未创建。



我宁愿使用最后一个构造函数,因为我不必相应地格式化字符串格式。

  var startDate = new Date(2014,12,14,19,0,0); 
var endDate = new Date(2015,1,21,19,0,0);

我将 startDate endDate ,以便我们看到警报。



  var endDate = new Date ,14,19,0,0); var startDate = new Date(2015,1,21,19,0,0); if(startDate> endDate){alert(结束日期不能小于开始日期) ;}  


I have two dates in DD/MM/YYYY HH:MM:SS format ,i want to compare two dates and throw an

alert .

I tried the below code,but it is not working.

startdate = "14/12/2014  19:00:00";
enddate = "21/01/2015  19:00:00";

if(new Date(startdate) > new Date(enddate))
{
    alert("End date cannot be less than start date");

}

解决方案

You can create a Date using the following constructors:

new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, date[, hour[, minutes[, seconds[, milliseconds]]]]]);

You have used the third of them, where the dateString is a

String value representing a date. The string should be in a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).

The string you have provided hasn't the correct format. Hence the corresponding date objects haven't been created.

I would prefer using the last constructor, since I wouldn't have to format correspondingly the strings.

var startDate = new Date(2014,12,14,19,0,0);
var endDate = new Date(2015,1,21,19,0,0);

I swapped the startDate with the endDate, in order we see the alert.

var endDate = new Date(2014,12,14,19,0,0);
var startDate = new Date(2015,1,21,19,0,0);

if(startDate > endDate)
{
    alert("End date cannot be less than start date");
}

这篇关于javascript比较两个日期并发出警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆