用JavaScript比较两个日期

有人可以建议一种使用JavaScript 比较两个大于,小于和过去的日期的值的方法吗?这些值将来自文本框。

MandyJinJin2020/03/09 19:17:28

Here is what I did in one of my projects,

function CompareDate(tform){
     var startDate = new Date(document.getElementById("START_DATE").value.substring(0,10));
     var endDate = new Date(document.getElementById("END_DATE").value.substring(0,10));

     if(tform.START_DATE.value!=""){
         var estStartDate = tform.START_DATE.value;
         //format for Oracle
         tform.START_DATE.value = estStartDate + " 00:00:00";
     }

     if(tform.END_DATE.value!=""){
         var estEndDate = tform.END_DATE.value;
         //format for Oracle
         tform.END_DATE.value = estEndDate + " 00:00:00";
     }

     if(endDate <= startDate){
         alert("End date cannot be smaller than or equal to Start date, please review you selection.");
         tform.START_DATE.value = document.getElementById("START_DATE").value.substring(0,10);
         tform.END_DATE.value = document.getElementById("END_DATE").value.substring(0,10);
         return false;
     }
}

calling this on form onsubmit. hope this helps.

TonyEvaL2020/03/09 19:17:27

An Improved version of the code posted by "some"

/* Compare the current date against another date.
 *
 * @param b  {Date} the other date
 * @returns   -1 : if this < b
 *             0 : if this === b
 *             1 : if this > b
 *            NaN : if a or b is an illegal date
*/ 
Date.prototype.compare = function(b) {
  if (b.constructor !== Date) {
    throw "invalid_date";
  }

 return (isFinite(this.valueOf()) && isFinite(b.valueOf()) ? 
          (this>b)-(this<b) : NaN 
        );
};

usage:

  var a = new Date(2011, 1-1, 1);
  var b = new Date(2011, 1-1, 1);
  var c = new Date(2011, 1-1, 31);
  var d = new Date(2011, 1-1, 31);

  assertEquals( 0, a.compare(b));
  assertEquals( 0, b.compare(a));
  assertEquals(-1, a.compare(c));
  assertEquals( 1, c.compare(a));
斯丁Sam斯丁2020/03/09 19:17:27

I usually store Dates as timestamps(Number) in databases.

When I need to compare, I simply compare among those timestamps or

convert it to Date Object and then compare with > <if necessary.

Note that == or === does not work properly unless your variables are references of the same Date Object.

Convert those Date objects to timestamp(number) first and then compare equality of them.


Date to Timestamp

var timestamp_1970 = new Date(0).getTime(); // 1970-01-01 00:00:00
var timestamp = new Date().getTime(); // Current Timestamp

Timestamp to Date

var timestamp = 0; // 1970-01-01 00:00:00
var DateObject = new Date(timestamp);
番长神无2020/03/09 19:17:27

In order to create dates from free text in Javascript you need to parse it into the Date() object.

You could use Date.parse() which takes free text tries to convert it into a new date but if you have control over the page I would recommend using HTML select boxes instead or a date picker such as the YUI calendar control or the jQuery UI Datepicker.

Once you have a date as other people have pointed out you can use simple arithmetic to subtract the dates and convert it back into a number of days by dividing the number (in seconds) by the number of seconds in a day (60*60*24 = 86400).

达蒙理查德2020/03/09 19:17:27

To compare two date we can use date.js JavaScript library which can be found at : https://code.google.com/archive/p/datejs/downloads

and use the Date.compare( Date date1, Date date2 ) method and it return a number which mean the following result:

-1 = date1 is lessthan date2.

0 = values are equal.

1 = date1 is greaterthan date2.

LEYEvaL2020/03/09 19:17:27

Via Moment.js

Jsfiddle: http://jsfiddle.net/guhokemk/1/

function compare(dateTimeA, dateTimeB) {
    var momentA = moment(dateTimeA,"DD/MM/YYYY");
    var momentB = moment(dateTimeB,"DD/MM/YYYY");
    if (momentA > momentB) return 1;
    else if (momentA < momentB) return -1;
    else return 0;
}

alert(compare("11/07/2015", "10/07/2015"));

The method returns 1 if dateTimeA is greater than dateTimeB

The method returns 0 if dateTimeA equals dateTimeB

The method returns -1 if dateTimeA is less than dateTimeB

理查德村村小宇宙2020/03/09 19:17:27

Just to add yet another possibility to the many existing options, you could try:

if (date1.valueOf()==date2.valueOf()) .....

...which seems to work for me. Of course you do have to ensure that both dates are not undefined...

if ((date1?date1.valueOf():0)==(date2?date2.valueOf():0) .....

This way we can ensure that a positive comparison is made if both are undefined also, or...

if ((date1?date1.valueOf():0)==(date2?date2.valueOf():-1) .....

...if you prefer them not to be equal.

小小2020/03/09 19:17:27
var date = new Date(); // will give you todays date.

// following calls, will let you set new dates.
setDate()   
setFullYear()   
setHours()  
setMilliseconds()   
setMinutes()    
setMonth()  
setSeconds()    
setTime()

var yesterday = new Date();
yesterday.setDate(...date info here);

if(date>yesterday)  // will compare dates
LJinJin2020/03/09 19:17:27
function datesEqual(a, b)
{
   return (!(a>b || b>a))
}
神无阳光2020/03/09 19:17:27

注意-仅比较日期部分:

当我们在javascript中比较两个日期时。还需要花费数小时,数分钟和数秒。因此,如果我们只需要比较日期,则可以采用以下方法:

var date1= new Date("01/01/2014").setHours(0,0,0,0);

var date2= new Date("01/01/2014").setHours(0,0,0,0);

现在:if date1.valueOf()> date2.valueOf()将像魅力一样工作。

Eva千羽2020/03/09 19:17:27

到目前为止,最简单的方法是从另一个日期中减去一个日期并比较结果。

var oDateOne = new Date();
var oDateTwo = new Date();

alert(oDateOne - oDateTwo === 0);
alert(oDateOne - oDateTwo < 0);
alert(oDateOne - oDateTwo > 0);

小小2020/03/09 19:17:27

仅比较日期(忽略时间部分):

Date.prototype.sameDay = function(d) {
  return this.getFullYear() === d.getFullYear()
    && this.getDate() === d.getDate()
    && this.getMonth() === d.getMonth();
}

用法:

if(date1.sameDay(date2)) {
    // highlight day on calendar or something else clever
}
小小阿飞2020/03/09 19:17:27

关系运算符< <= > >=可用于比较JavaScript日期:

var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 2);
d1 <  d2; // true
d1 <= d2; // true
d1 >  d2; // false
d1 >= d2; // false

However, the equality operators == != === !== cannot be used to compare (the value of) dates because:

  • Two distinct objects are never equal for either strict or abstract comparisons.
  • An expression comparing Objects is only true if the operands reference the same Object.

You can compare the value of dates for equality using any of these methods:

var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 1);
/*
 * note: d1 == d2 returns false as described above
 */
d1.getTime() == d2.getTime(); // true
d1.valueOf() == d2.valueOf(); // true
Number(d1)   == Number(d2);   // true
+d1          == +d2;          // true

Both Date.getTime() and Date.valueOf() return the number of milliseconds since January 1, 1970, 00:00 UTC. Both Number function and unary + operator call the valueOf() methods behind the scenes.

Cathy2020/03/09 19:17:27

在javascript中比较日期的最简单方法是先将其转换为Date对象,然后再比较这些date-objects。

在下面找到具有三个功能的对象:

  • date.compare(a,b)

    返回一个数字:

    • 如果a <b则为-1
    • 如果a = b,则为0
    • 如果a> b为1
    • 如果a或b是非法日期,则为NaN
  • date.inRange(d,start,end)

    返回一个布尔值或NaN:

    • 如果d开始结束之间(包括端点),则为true
    • 如果d开始之前结束之后,则返回false
    • 如果一个或多个日期不合法,则为NaN。
  • date.convert

    由其他函数用于将其输入转换为日期对象。输入可以是

    • 一个日期 -object:输入返回原样。
    • 一个数组:解释为[年,月,日。注意月份是0-11。
    • 一个数字:解释为自1970年1月1日以来的毫秒数(时间戳)
    • 一个字符串:几个不同的格式支持,如“YYYY / MM / DD”, “MM / DD / YYYY”, “2009年1月31日”等等。
    • 一个对象:解释为具有年,月和日属性的对象。 注意月份是0-11。

// Source: http://stackoverflow.com/questions/497790
var dates = {
    convert:function(d) {
        // Converts the date in d to a date-object. The input can be:
        //   a date object: returned without modification
        //  an array      : Interpreted as [year,month,day]. NOTE: month is 0-11.
        //   a number     : Interpreted as number of milliseconds
        //                  since 1 Jan 1970 (a timestamp) 
        //   a string     : Any format supported by the javascript engine, like
        //                  "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
        //  an object     : Interpreted as an object with year, month and date
        //                  attributes.  **NOTE** month is 0-11.
        return (
            d.constructor === Date ? d :
            d.constructor === Array ? new Date(d[0],d[1],d[2]) :
            d.constructor === Number ? new Date(d) :
            d.constructor === String ? new Date(d) :
            typeof d === "object" ? new Date(d.year,d.month,d.date) :
            NaN
        );
    },
    compare:function(a,b) {
        // Compare two dates (could be of any type supported by the convert
        // function above) and returns:
        //  -1 : if a < b
        //   0 : if a = b
        //   1 : if a > b
        // NaN : if a or b is an illegal date
        // NOTE: The code inside isFinite does an assignment (=).
        return (
            isFinite(a=this.convert(a).valueOf()) &&
            isFinite(b=this.convert(b).valueOf()) ?
            (a>b)-(a<b) :
            NaN
        );
    },
    inRange:function(d,start,end) {
        // Checks if date in d is between dates in start and end.
        // Returns a boolean or NaN:
        //    true  : if d is between start and end (inclusive)
        //    false : if d is before start or after end
        //    NaN   : if one or more of the dates is illegal.
        // NOTE: The code inside isFinite does an assignment (=).
       return (
            isFinite(d=this.convert(d).valueOf()) &&
            isFinite(start=this.convert(start).valueOf()) &&
            isFinite(end=this.convert(end).valueOf()) ?
            start <= d && d <= end :
            NaN
        );
    }
}
神无Green2020/03/09 19:17:27

Date对象会做你想要的东西-构造一个每个日期,然后用它们进行比较><<=>=

==!====,和!==运营商要求使用date.getTime()作为

var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();

要清楚的是,仅直接检查日期对象是否相等将不起作用

var d1 = new Date();
var d2 = new Date(d1);

console.log(d1 == d2);   // prints false (wrong!) 
console.log(d1 === d2);  // prints false (wrong!)
console.log(d1 != d2);   // prints true  (wrong!)
console.log(d1 !== d2);  // prints true  (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)

我建议您使用下拉列表或日期输入的某些类似约束形式,而不要使用文本框,以免您陷入输入验证的困境。