用JavaScript比较两个日期

谁能提出一种方法,用JavaScript比较两个日期的值是否大于、小于和不在过去?这些值将来自文本框。

对该问题的评论 (5)
解决办法

Date对象将做你想做的事--为每个日期构造一个,然后用>、`

评论(21)

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

下面你会发现一个对象有三个函数。

  • dates.compare(a,b)

返回一个数字。

  • 如果a < b

  • 0,如果a=b

  • 1,如果a > b

  • 如果a或b为非法日期,则为NaN。

  • dates.inRange (d,start,end)

返回一个布尔值或NaN值,如果d开始结束之间,则true

  • 如果d位于开始结束之间,则返回true

  • 如果d开始之前或结束之后,则为false

  • 如果一个或多个日期是非法的,则为NaN。

  • 如果一个或多个日期是非法的,则为NaN.

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

  • 一个日期对象。 输入的日期按原样返回。
  • 一个数组。 解释为[年,月,日]。 注意月份是0-11。
  • 数**:解释为[年、月、日]。 解释为 1970 年 1 月 1 日以来的毫秒数(时间戳)。
  • 一个字符串。 支持多种不同的格式,如"YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" 等。
  • 一个对象。 解释为一个具有年、月、日期属性的对象。 注意月份是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
评论(3)

像往常一样比较<>,但凡涉及=的,都应该使用+前缀。 就像这样。

var x = new Date('2013-05-23');
var y = new Date('2013-05-23');

// less than, greater than is fine:
x < y; => false
x > y; => false
x === y; => false, oops!

// anything involving '=' should use the '+' prefix
// it will then compare the dates' millisecond values
+x  true
+x >= +y;  => true
+x === +y; => true

希望对大家有所帮助!

评论(8)

关系运算符<```<=``>``>=可以用来比较JavaScript日期。

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

但是,平等运算符==``!==````!==不能用来比较(日期的值)[因为][1]。

  • 无论是严格的还是抽象的比较,两个不同的对象永远不会相等。 严格或抽象比较的两个不同对象永远不会相等。
  • 只有当操作数引用同一个对象时,比较对象的表达式才是真的。

你可以使用这些方法中的任何一种来比较日期的值是否相等。

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

[Date.getTime()][2]和Date.valueOf()都返回1970年1月1日00:00 UTC以来的毫秒数。 Number函数和一元+运算符都在幕后调用valueOf()方法。

[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators [2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime

评论(3)

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

<!--开始片段。 js hide: false console.true babel: true true babel.false --> -- begin snippet: js hide: false console: true false -->

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

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

<!--结束片段-->

评论(0)

在JavaScript中比较日期很容易... JavaScript有内置的日期**比较系统,这使得比较变得非常简单......

只要按照以下步骤来比较2个日期值,例如你有2个输入,每个输入都有一个String的日期值,你要比较它们...

1.你有2个输入的字符串值,你想比较它们,它们如下。

var date1 = '01/12/2018';
var date2 = '12/12/2018';

2.它们需要成为Date Object才能作为日期值进行比较,所以只需将它们转换为日期,使用new Date(),我只是为了简单的解释而重新分配它们,但你可以按照你喜欢的方式进行。

date1 = new Date(date1);
date2 = new Date(date2);

3.现在简单地比较一下,使用>``<``>=``<=


date1 > date2;  //false
date1 < date2;  //true
date1 >= date2; //false
date1 
评论(4)

只比较一天(忽略时间部分)。

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

用法: {{{5510095}}

if(date1.sameDay(date2)) {
    // highlight day on calendar or something else clever
}
评论(2)

什么格式?

如果你构建一个Javascript的Date对象,你可以直接减去它们,得到一个毫秒的差异(编辑:或者直接比较它们) 。

js>t1 = new Date()
Thu Jan 29 2009 14:19:28 GMT-0500 (Eastern Standard Time)
js>t2 = new Date()
Thu Jan 29 2009 14:19:31 GMT-0500 (Eastern Standard Time)
js>t2-t1
2672
js>t3 = new Date('2009 Jan 1')
Thu Jan 01 2009 00:00:00 GMT-0500 (Eastern Standard Time)
js>t1-t3
2470768442
js>t1>t3
true
评论(6)

简答

下面是一个函数,如果from dateTime &gt.to dateTime [Demo in action][1]返回{boolean}。 到 dateTime [Demo in action][1],则返回{boolean}。

var from = '08/19/2013 00:00'
var to = '08/12/2013 00:00 '

function isFromBiggerThanTo(dtmfrom, dtmto){
   return new Date(dtmfrom).getTime() >=  new Date(dtmto).getTime() ;
}
console.log(isFromBiggerThanTo(from, to)); //true

解释

[jsFiddle][2]

var date_one = '2013-07-29 01:50:00',
date_two = '2013-07-29 02:50:00';
//getTime() returns the number of milliseconds since 01.01.1970.
var timeStamp_date_one = new Date(date_one).getTime() ; //1375077000000 
console.log(typeof timeStamp_date_one);//number 
var timeStamp_date_two = new Date(date_two).getTime() ;//1375080600000 
console.log(typeof timeStamp_date_two);//number 

因为你现在有两个数字类型的日期时间。 你可以用任何比较操作来比较它们

( >, < ,= ,!= ,== ,!== ,>= AND <=)

然后

如果你熟悉 "C#"自定义日期和时间格式字符串,这个库应该做同样的事情,并帮助你格式化你的日期和时间dtmFRM,无论你传递的是日期时间字符串还是unix格式。

使用情况

var myDateTime = new dtmFRM();

alert(myDateTime.ToString(1375077000000, "MM/dd/yyyy hh:mm:ss ampm"));
//07/29/2013 01:50:00 AM

alert(myDateTime.ToString(1375077000000,"the year is yyyy and the day is dddd"));
//this year is 2013 and the day is Monday

alert(myDateTime.ToString('1/21/2014', "this month is MMMM and the day is dd"));
//this month is january and the day is 21

[演示][4]

你所要做的就是在库中传递这些格式的任何一个 "js "文件。

[1]: http://jsfiddle.net/NTghK/ [2]: http://jsfiddle.net/minagabriel/Fu7Ag/1/ 3:

[4]:

评论(2)

你使用这个代码。

var firstValue = "2012-05-12".split('-');
var secondValue = "2014-07-12".split('-');

 var firstDate=new Date();
 firstDate.setFullYear(firstValue[0],(firstValue[1] - 1 ),firstValue[2]);

 var secondDate=new Date();
 secondDate.setFullYear(secondValue[0],(secondValue[1] - 1 ),secondValue[2]);     

  if (firstDate > secondDate)
  {
   alert("First Date  is greater than Second Date");
  }
 else
  {
    alert("Second Date  is greater than First Date");
  }

也可以查看这个链接 http://www.w3schools.com/js/js_obj_date.asp

评论(2)

注意 - 只比较日期部分:

当我们在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()就能正常工作。

评论(0)
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
评论(0)
function datesEqual(a, b)
{
   return (!(a>b || b>a))
}
评论(3)

为了在现有的众多选项中增加另一种可能性,您可以尝试。

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

...这似乎对我有效。 当然,你必须确保两个日期都不是未定义的......

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

这样我们就可以确保在两者都未定义的情况下进行正向比较,或者... ...

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

...如果你希望他们不平等的话。

评论(0)

通过[Moment.js][1]

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"));

如果 "dateTimeA "大于 "dateTimeB",方法返回1。

如果dateTimeA'等于dateTimeB',方法返回0。

如果dateTimeA'小于dateTimeB',方法返回-1。

[1]: https://momentjs.com/

评论(3)

注意时区

一个javascript日期没有时区的概念。 它是时间中的一个时刻(自纪元起的时间),具有方便的功能,用于翻译成"local&quot.的字符串。 时区的字符串之间的转换。 如果你想使用日期对象来处理日期,就像这里的每个人都在做的那样,**你希望你的日期在相关日期的开始时代表UTC午夜。 所以你需要非常警惕地管理时区的概念,特别是当你创建午夜UTC日期对象的时候。

大多数时候,你会希望你的日期能够反映用户的时区。 如果今天是你的生日,请点击。 新西兰和美国的用户在同一时间点击会得到不同的日期。 在这种情况下,可以这样做...

// create a date (utc midnight) reflecting the value of myDate and the environment's timezone offset.
new Date(Date.UTC(myDate.getFullYear(),myDate.getMonth(), myDate.getDate()));

有时,国际可比性胜过本地准确性。 在这种情况下,可以这样做...

// the date in London of a moment in time. Device timezone is ignored.
new Date(Date.UTC(myDate.getUTCYear(), myDate.getyUTCMonth(), myDate.getUTCDate()));

**现在你可以像其他答案所建议的那样,直接比较你的日期对象。

在创建时注意管理时区后,当你转换回字符串表示时,你也需要确保时区不被破坏。 所以你可以安全地使用......

  • toISOString()
  • "getUTCxxx()"。
  • `getTime() //返回一个没有时间或时区的数字。
  • `.toLocaleDateString("fr",{timezone:"UTC"}) //你想要的任何时区,但总是UTC。

完全避免使用其他的东西,尤其是...

  • getYear(),getMonth(),getDate()
评论(0)

将两个日期相减得到毫秒的差值,如果得到 "0",则是同一个日期。

<!-language=lang-js-->

function areSameDate(d1, d2){
    return d1 - d2 === 0
}
评论(0)

要比较两个日期,我们可以使用date.js JavaScript库,它可以在.net上找到。 [https://code.google.com/archive/p/datejs/downloads][1]

[1]: https://code.google.com/archive/p/datejs/downloads

并使用Date.compare( Date date1, Date date2 )方法,它返回一个,意味着以下结果。

-1 = date1比date2少。

0 = 数值相等,1 = date1大于date2。

1 = date1大于date2.

评论(0)

为了在Javascript中从自由文本中创建日期,你需要将其解析为Date()对象。

你可以使用Date.parse(),它可以尝试将自由文本转换成一个新的日期,但是如果你可以控制页面,我建议使用HTML选择框或者日期选择器,比如[YUI日历控件][1]或者[jQuery UI Datepicker][2]。

一旦你有了一个日期,就像其他人指出的那样,你可以使用简单的算术来减去日期,并通过将数字(以秒为单位)除以一天中的秒数(606024 = 86400)来将其转换为天数。

[1]: http://developer.yahoo.com/yui/calendar/ [2]: http://docs.jquery.com/UI/Datepicker

评论(0)

简单的方法就是。

var first = '2012-11-21';
var second = '2012-11-03';

if (new Date(first) > new Date(second) {
    .....
}
评论(0)