2449

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

4

42 回答 42

2934

Date 对象将执行您想要的操作 - 为每个日期构造一个,然后使用、>或比较它们。<<=>=

, ==,!=和运算===!==要求您使用date.getTime()as in

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)

不过,我建议您使用下拉菜单或一些类似的受限日期输入形式而不是文本框,以免您发现自己陷入输入验证地狱。


对于好奇的date.getTime()文档

返回指定日期的数值,作为自 1970 年 1 月 1 日 00:00:00 UTC 以来的毫秒数。(之前的时间返回负值。)

于 2009-01-29T19:20:10.787 回答
475

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

您可以在下面找到一个具有三个功能的对象:

  • 日期.比较(a,b)

    返回一个数字:

    • -1 如果 a < b
    • 0 如果 a = b
    • 1 如果 a > b
    • 如果 a 或 b 是非法日期,则为 NaN
  • 日期.inRange(d,开始,结束)

    返回一个布尔值或 NaN:

    • 如果d开始结束(包括)之间,则为
    • 如果dstart之前或end之后,则为false
    • 如果一个或多个日期是非法的,则为 NaN。
  • 日期转换

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

    • a date -object :输入按原样返回。
    • 一个数组:解释为 [年、月、日]。注意月份是 0-11。
    • 一个数字:解释为自 1970 年 1 月 1 日以来的毫秒数(时间戳)
    • 一个字符串:支持几种不同的格式,如“YYYY/MM/DD”、“MM/DD/YYYY”、“2009 年 1 月 31 日”等。
    • an object:解释为具有年、月、日属性的对象。 注意月份是 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
        );
    }
}
于 2009-01-31T00:18:07.330 回答
419

像往常一样比较<和,但任何涉及或应该使用前缀的东西。像这样:>=====+

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

// less than, greater than is fine:
console.log('x < y', x < y); // false
console.log('x > y', x > y); // false
console.log('x <= y', x <= y); // true
console.log('x >= y', x >= y); // true
console.log('x === y', x === y); // false, oops!

// anything involving '==' or '===' should use the '+' prefix
// it will then compare the dates' millisecond values

console.log('+x === +y', +x === +y); // true

于 2013-05-23T12:21:09.730 回答
189

关系运算符< <= > >=可用于比较 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

但是,等式运算符== != === !==不能用于比较日期(的值),因为

  • 对于严格或抽象比较,两个不同的对象永远不会相等。
  • 仅当操作数引用相同的对象时,比较对象的表达式才为真。

您可以使用以下任何方法比较日期值是否相等:

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()返回Date.valueOf()自 1970 年 1 月 1 日 00:00 UTC 以来的毫秒数。Number函数和一元运算符都在后台+调用方法。valueOf()

于 2013-01-31T16:04:16.903 回答
95

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

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

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

于 2011-11-01T00:48:12.353 回答
87

在 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 <= date2; //true

比较javascript中的日期

于 2017-07-11T09:59:46.477 回答
52

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

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
}

我不再建议修改prototype内置对象的。试试这个:

function isSameDay(d1, d2) {
  return d1.getFullYear() === d2.getFullYear() &&
    d1.getDate() === d2.getDate() &&
    d1.getMonth() === d2.getMonth();
}


console.log(isSameDay(new Date('Jan 15 2021 02:39:53 GMT-0800'), new Date('Jan 15 2021 23:39:53 GMT-0800')));
console.log(isSameDay(new Date('Jan 15 2021 10:39:53 GMT-0800'), new Date('Jan 16 2021 10:39:53 GMT-0800')));

注意您的时区将返回年/月/日;如果您想检查两个日期是否在不同时区的同一天,我建议使用时区感知库。

例如

> (new Date('Jan 15 2021 01:39:53 Z')).getDate()  // Jan 15 in UTC
14  // Returns "14" because I'm in GMT-08
于 2013-09-27T15:38:23.410 回答
39

什么格式?

如果您构造一个 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
于 2009-01-29T19:19:21.583 回答
22

简单的方法是,

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

if (new Date(first) > new Date(second) {
    .....
}
于 2019-06-28T06:47:49.670 回答
21

注意 - 仅比较日期部分:

当我们在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()将像魅力一样工作。

于 2017-03-14T17:10:14.773 回答
18

简短的回答

这是一个返回 {boolean} 的函数,如果从 dateTime > 到 dateTime演示正在运行

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

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 <=)

然后

如果您熟悉自定义日期和时间格式字符串,则无论您是传入日期时间字符串还是 unix 格式,C#此库都应该执行完全相同的操作并帮助您格式化日期和时间dtmFRM

用法

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

演示

您所要做的就是在库js文件中传递任何这些格式

于 2013-08-02T21:06:16.267 回答
17

您使用此代码,

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

于 2012-08-09T10:49:00.450 回答
14
function datesEqual(a, b)
{
   return (!(a>b || b>a))
}
于 2009-07-20T03:36:57.953 回答
13
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
于 2009-01-29T19:17:51.680 回答
12

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

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

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

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

于 2016-07-05T05:53:00.543 回答
12

当心时区

javascript 日期没有 timezone 的概念。这是一个时间点(自纪元以来的滴答声),具有用于在“本地”时区中转换字符串和从字符串转换的便捷功能。如果您想使用日期对象处理日期,就像这里的每个人都在做的那样,您希望您的日期代表相关日期开始时的 UTC 午夜。这是一个常见且必要的约定,可让您使用日期,而不管其创建的季节或时区如何。因此,您需要非常警惕地管理时区的概念,尤其是在您创建午夜 UTC Date 对象时。

大多数时候,您会希望您的日期反映用户的时区。如果今天是您的生日,请单击。新西兰和美国的用户同时点击并获得不同的日期。在这种情况下,这样做...

// 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() //returns a number with no time or timezone.
  • .toLocaleDateString("fr",{timezone:"UTC"}) // whatever locale you want, but ALWAYS UTC.

并完全避免其他一切,尤其是...

  • getYear(), getMonth(),getDate()
于 2017-10-20T09:51:47.973 回答
11

只是为许多现有选项添加另一种可能性,您可以尝试:

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

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

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

这样,如果两者都未定义,我们可以确保进行正比较,或者......

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

...如果您希望它们不相等。

于 2014-03-26T15:41:05.623 回答
9

减去两个日期得到毫秒的差异,如果你得到0它是相同的日期

function areSameDate(d1, d2){
    return d1 - d2 === 0
}
于 2012-11-15T09:54:18.180 回答
8

假设你得到了日期对象 A 和 B,得到它们的 EPOC 时间值,然后减去得到以毫秒为单位的差异。

var diff = +A - +B;

就这样。

于 2011-07-23T03:03:35.653 回答
8

如果以下是您的日期格式,则可以使用此代码:

var first = '2012-11-21';
var second = '2012-11-03';
if(parseInt(first.replace(/-/g,""),10) > parseInt(second.replace(/-/g,""),10)){
   //...
}

它将检查20121121数字是否大于20121103或不大于。

于 2012-06-23T14:08:15.677 回答
8

要比较两个日期,我们可以使用 date.js JavaScript 库,该库位于:https ://code.google.com/archive/p/datejs/downloads

并使用该Date.compare( Date date1, Date date2 )方法并返回一个数字,表示以下结果:

-1 = date1 小于 date2。

0 = 值相等。

1 = date1 大于 date2。

于 2016-08-31T17:00:39.267 回答
7

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

您可以使用 Date.parse() 尝试将自由文本转换为新日期,但如果您可以控制页面,我建议您使用 HTML 选择框或日期选择器,例如YUI 日历控件jQuery UI日期选择器

一旦您有其他人指出的日期,您可以使用简单的算术减去日期并将其转换回天数,方法是将数字(以秒为单位)除以一天中的秒数(60 * 60 * 24 = 86400)。

于 2009-01-29T19:35:19.773 回答
7

表现

今天 2020.02.27 我在 MacOs High Sierra v10.13.6 上的 Chrome v80.0、Safari v13.0.5 和 Firefox 73.0.1 上执行所选解决方案的测试

结论

  • 解决方案d1==d2(D) 和d1===d2(E) 对于所有浏览器都是最快的
  • 解决方案getTime(A) 比 valueOf(B) 快(两者都是中快)
  • 解决方案 F,L,N 对于所有浏览器来说都是最慢的

在此处输入图像描述

细节

下面介绍了性能测试中使用的代码段解决方案。您可以在您的机器上进行测试这里

function A(d1,d2) {
	return d1.getTime() == d2.getTime();
}

function B(d1,d2) {
	return d1.valueOf() == d2.valueOf();
}

function C(d1,d2) {
	return Number(d1)   == Number(d2);
}

function D(d1,d2) {
	return d1 == d2;
}

function E(d1,d2) {
	return d1 === d2;
}

function F(d1,d2) {
	return (!(d1>d2 || d2>d1));
}

function G(d1,d2) {
	return d1*1 == d2*1;
}

function H(d1,d2) {
	return +d1 == +d2;
}

function I(d1,d2) {
	return !(+d1 - +d2);
}

function J(d1,d2) {
	return !(d1 - d2);
}

function K(d1,d2) {
	return d1 - d2 == 0;
}

function L(d1,d2) {
	return !((d1>d2)-(d1<d2));
}

function M(d1,d2) {
  return d1.getFullYear() === d2.getFullYear()
    && d1.getDate() === d2.getDate()
    && d1.getMonth() === d2.getMonth();
}

function N(d1,d2) {
	return (isFinite(d1.valueOf()) && isFinite(d2.valueOf()) ? !((d1>d2)-(d1<d2)) : false );
}


// TEST

let past= new Date('2002-12-24'); // past
let now= new Date('2020-02-26');  // now

console.log('Code  d1>d2  d1<d2  d1=d2')
var log = (l,f) => console.log(`${l}     ${f(now,past)}  ${f(past,now)}  ${f(now,now)}`);

log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('G',G);
log('H',H);
log('I',I);
log('J',J);
log('K',K);
log('L',L);
log('M',M);
log('N',N);
p {color: red}
<p>This snippet only presents tested solutions (it not perform tests itself)</p>

铬的结果

在此处输入图像描述

于 2020-02-27T18:54:33.947 回答
6
var date_today=new Date();
var formated_date = formatDate(date_today);//Calling formatDate Function

var input_date="2015/04/22 11:12 AM";

var currentDateTime = new Date(Date.parse(formated_date));
var inputDateTime   = new Date(Date.parse(input_date));

if (inputDateTime <= currentDateTime){
    //Do something...
}

function formatDate(date) {
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'PM' : 'AM';

    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    hours   = hours < 10 ? '0'+hours : hours ;

    minutes = minutes < 10 ? '0'+minutes : minutes;

    var strTime = hours+":"+minutes+ ' ' + ampm;
    return  date.getFullYear()+ "/" + ((date.getMonth()+1) < 10 ? "0"+(date.getMonth()+1) :
    (date.getMonth()+1) ) + "/" + (date.getDate() < 10 ? "0"+date.getDate() :
    date.getDate()) + " " + strTime;
}
于 2015-05-06T11:25:28.447 回答
5

“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 
        );
};

用法:

  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));
于 2011-08-20T04:02:04.713 回答
5

我通常存储Datestimestamps(Number)数据库中。

当我需要比较时,我只是比较这些时间戳或

将其转换为日期对象,然后> <在必要时进行比较。

请注意,== 或 === 不能正常工作,除非您的变量是同一日期对象的引用。

首先将这些 Date 对象转换为时间戳(数字),然后比较它们的相等性。


日期到时间戳

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

迄今为止的时间戳

var timestamp = 0; // 1970-01-01 00:00:00
var DateObject = new Date(timestamp);
于 2012-08-22T01:40:14.863 回答
3

在比较Dates对象之前,请尝试将它们的毫秒数都设置为零,例如Date.setMilliseconds(0);.

在某些情况下,Date对象是在 javascript 中动态创建的,如果您继续打印Date.getTime(),您会看到毫秒数发生变化,这将阻止两个日期相等。

于 2013-10-24T17:34:25.213 回答
2

假设您处理这种2014[:-/.]06[:-/.]06或这种06[:-/.]06[:-/.]2014日期格式,那么您可以通过这种方式比较日期

var a = '2014.06/07', b = '2014-06.07', c = '07-06/2014', d = '07/06.2014';

parseInt(a.replace(/[:\s\/\.-]/g, '')) == parseInt(b.replace(/[:\s\/\.-]/g, '')); // true
parseInt(c.replace(/[:\s\/\.-]/g, '')) == parseInt(d.replace(/[:\s\/\.-]/g, '')); // true
parseInt(a.replace(/[:\s\/\.-]/g, '')) < parseInt(b.replace(/[:\s\/\.-]/g, '')); // false
parseInt(c.replace(/[:\s\/\.-]/g, '')) > parseInt(d.replace(/[:\s\/\.-]/g, '')); // false

如您所见,我们去除分隔符,然后比较整数。

于 2014-06-23T22:22:18.493 回答
1
        from_date ='10-07-2012';
        to_date = '05-05-2012';
        var fromdate = from_date.split('-');
        from_date = new Date();
        from_date.setFullYear(fromdate[2],fromdate[1]-1,fromdate[0]);
        var todate = to_date.split('-');
        to_date = new Date();
        to_date.setFullYear(todate[2],todate[1]-1,todate[0]);
        if (from_date > to_date ) 
        {
            alert("Invalid Date Range!\nStart Date cannot be after End Date!")

            return false;
        }

使用此代码使用 javascript 比较日期。

谢谢 D.Jeeva

于 2012-07-10T10:20:12.907 回答
1
var curDate=new Date();
var startDate=document.forms[0].m_strStartDate;

var endDate=document.forms[0].m_strEndDate;
var startDateVal=startDate.value.split('-');
var endDateVal=endDate.value.split('-');
var firstDate=new Date();
firstDate.setFullYear(startDateVal[2], (startDateVal[1] - 1), startDateVal[0]);

var secondDate=new Date();
secondDate.setFullYear(endDateVal[2], (endDateVal[1] - 1), endDateVal[0]);
if(firstDate > curDate) {
    alert("Start date cannot be greater than current date!");
    return false;
}
if (firstDate > secondDate) {
    alert("Start date cannot be greater!");
    return false;
}
于 2013-02-12T10:31:13.633 回答
1

这是我在我的一个项目中所做的,

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;
     }
}

在表单提交时调用它。希望这可以帮助。

于 2013-09-20T15:37:31.070 回答
1

嗨,这是我比较日期的代码。就我而言,我正在检查不允许选择过去的日期。

var myPickupDate = <pick up date> ;
var isPastPickupDateSelected = false;
var currentDate = new Date();

if(currentDate.getFullYear() <= myPickupDate.getFullYear()){
    if(currentDate.getMonth()+1 <= myPickupDate.getMonth()+1 || currentDate.getFullYear() < myPickupDate.getFullYear()){
                        if(currentDate.getDate() <= myPickupDate.getDate() || currentDate.getMonth()+1 < myPickupDate.getMonth()+1 || currentDate.getFullYear() < myPickupDate.getFullYear()){
                                            isPastPickupDateSelected = false;
                                            return;
                                        }
                    }
}
console.log("cannot select past pickup date");
isPastPickupDateSelected = true;
于 2016-04-08T13:45:34.807 回答
1

比较两个日期的另一种方法是通过toISOString()方法。这在与保存在字符串中的固定日期进行比较时特别有用,因为您可以避免创建短暂的对象。凭借 ISO 8601 格式,您可以按字典顺序比较这些字符串(至少在您使用相同时区时)。

我不一定说它比使用时间对象或时间戳更好;只是提供这个作为另一种选择。这可能会失败,但我还没有偶然发现它们:)

于 2016-11-09T18:22:28.730 回答
1

上面给出的所有答案只解决了一件事:比较两个日期。

确实,它们似乎是问题的答案,但缺少很大一部分:

如果我想检查一个人是否已满 18 岁,该怎么办?

不幸的是,以上给出的答案都无法回答这个问题。

例如,当前时间(大约是我开始输入这些单词的时间)是 Fri Jan 31 2020 10:41:04 GMT-0600(Central Standard Time),而客户输入他的出生日期为“01/31 /2002”。

如果我们使用"365 days/year",也就是"31536000000"毫秒,我们会得到以下结果:

       let currentTime = new Date();
       let customerTime = new Date(2002, 1, 31);
       let age = (currentTime.getTime() - customerTime.getTime()) / 31536000000
       console.log("age: ", age);

带有以下打印输出:

       age: 17.92724710838407

但从法律上讲,该客户已经 18 岁。即使他输入“01/30/2002”,结果仍然是

       age: 17.930039743467784

小于18。系统会报“under age”错误。

这将持续到“01/29/2002”、“01/28/2002”、“01/27/2002”……“01/05/2002”,直到“01/04/2002”。

这样的系统只会杀死所有出生在 18 岁 0 天和 18 岁 26 天前的客户,因为他们在法律上是 18 岁,而系统显示“未满年龄”。

以下是对此类问题的回答:

invalidBirthDate: 'Invalid date. YEAR cannot be before 1900.',
invalidAge: 'Invalid age. AGE cannot be less than 18.',

public static birthDateValidator(control: any): any {
    const val = control.value;
    if (val != null) {
        const slashSplit = val.split('-');
        if (slashSplit.length === 3) {
            const customerYear = parseInt(slashSplit[0], 10);
            const customerMonth = parseInt(slashSplit[1], 10);
            const customerDate = parseInt(slashSplit[2], 10);
            if (customerYear < 1900) {
                return { invalidBirthDate: true };
            } else {
                const currentTime = new Date();
                const currentYear = currentTime.getFullYear();
                const currentMonth = currentTime.getMonth() + 1;
                const currentDate = currentTime.getDate();
                if (currentYear - customerYear < 18) {
                    return { invalidAge: true };
                } else if (
                    currentYear - customerYear === 18 &&
                    currentMonth - customerMonth < 0) {
                    return { invalidAge: true };
                } else if (
                    currentYear - customerYear === 18 &&
                    currentMonth - customerMonth === 0 &&
                    currentDate - customerDate < 0) {
                    return { invalidAge: true };
                } else {
                    return null;
                }
            }
        }
    }
}
于 2020-01-31T17:27:06.770 回答
0

您可以以最简单易懂的方式进行日期比较。

<input type="date" id="getdate1" />
<input type="date" id="getdate2" />

假设您有两个要比较它们的日期输入。

所以先写一个常用的方法来解析日期。

 <script type="text/javascript">
            function parseDate(input) {
             var datecomp= input.split('.'); //if date format 21.09.2017

              var tparts=timecomp.split(':');//if time also giving
              return new Date(dparts[2], dparts[1]-1, dparts[0], tparts[0], tparts[1]);
// here new date(  year, month, date,)
            }
        </script>

parseDate() 是用于解析日期的常用方法。现在您可以检查您的日期 =、>、< 任何类型的比较

    <script type="text/javascript">

              $(document).ready(function(){
              //parseDate(pass in this method date);
                    Var Date1=parseDate($("#getdate1").val());
                        Var Date2=parseDate($("#getdate2").val());
               //use any oe < or > or = as per ur requirment 
               if(Date1 = Date2){
         return false;  //or your code {}
}
 });
    </script>

当然,这段代码会帮助你。

于 2017-09-20T11:11:40.503 回答
0

我对这个问题的简单回答

checkDisabled(date) {
    const today = new Date()
    const newDate = new Date(date._d)
    if (today.getTime() > newDate.getTime()) {
        return true
    }
    return false
}
       
于 2021-10-28T15:55:29.927 回答
-1

试试这个,而比较日期应该是 iso 格式“yyyy-MM-dd”如果你只想比较日期使用这个 datehelper

<a href="https://plnkr.co/edit/9N8ZcC?p=preview"> Live Demo</a>
于 2017-06-15T12:42:21.430 回答
-1

使用 momentjs 进行日期操作。


通过使用检查一个日期与另一个日期相同或之后

isSameOrAfter() 方法

moment('2010-10-20').isSameOrAfter('2010-10-20') //true;

使用 isAfter() 方法检查一个日期之后是另一个日期

moment('2020-01-20').isAfter('2020-01-21'); // false
moment('2020-01-20').isAfter('2020-01-19'); // true

使用 isBefore() 方法检查一个日期在另一个之前。

moment('2020-01-20').isBefore('2020-01-21'); // true
moment('2020-01-20').isBefore('2020-01-19'); // false

使用 isSame() 方法检查一个日期与另一个日期相同

moment('2020-01-20').isSame('2020-01-21'); // false
moment('2020-01-20').isSame('2020-01-20'); // true
于 2021-03-16T07:17:30.680 回答
-1
function compare_date(date1, date2){
const x = new Date(date1)
const y = new Date(date2)
function checkyear(x, y){
    if(x.getFullYear()>y.getFullYear()){
        return "Date1 > Date2"
    }
    else if(x.getFullYear()<y.getFullYear()){
        return "Date2 > Date1"
    }
    else{
        return checkmonth(x, y)
    }
}
function checkmonth(x, y){
    if(x.getMonth()>y.getFullYear()){
        return "Date1 > Date2"
    }
    else if(x.getMonth()<y.getMonth){
        return "Date2 > Date1"
    }
    else {
        return checkDate(x, y)
    }
}
function checkDate(x, y){
    if(x.getDate()>y.getFullYear()){
        return "Date1 > Date2"
    }
    else if(x.getDate()<y.getDate()){
        return "Date2 > Date1"
    }
    else {
        return checkhour(x,y)
    }
}
function checkhour(x, y){
    if(x.getHours()>y.getHours()){
        return "Date1 > Date2"
    }
    else if(x.getHours()<y.getHours()){
        return "Date2 > Date1"
    }
    else {
        return checkhmin(x,y)
    }
}
function checkhmin(x,y){
    if(x.getMinutes()>y.getMinutes()){
        return "Date1 > Date2"
    }
    else if(x.getMinutes()<y.getMinutes()){
        return "Date2 > Date1"
    }
    else {
        return "Date1 = Date2"
    }
}
return checkyear(x, y)
于 2021-07-28T13:17:20.160 回答
-2

尝试使用此代码

var f =date1.split("/");

var t =date2.split("/");

var x =parseInt(f[2]+f[1]+f[0]);

var y =parseInt(t[2]+t[1]+t[0]);

if(x > y){
    alert("date1 is after date2");
}

else if(x < y){
    alert("date1 is before date2");
}

else{
    alert("both date are same");
}
于 2014-01-30T04:42:01.510 回答
-2
If you are using **REACT OR REACT NATIVE**, use this and it will work (Working like charm)

如果两个日期相同,则返回 TRUE,否则返回 FALSE

const compareDate = (dateVal1, dateVal2) => {
        if (dateVal1.valueOf() === dateVal2.valueOf()){
            return true;
        }
        else { return false;}
    }
于 2020-12-29T21:05:58.233 回答
-8

日期比较:

var str1  = document.getElementById("Fromdate").value;
var str2  = document.getElementById("Todate").value;
var dt1   = parseInt(str1.substring(0,2),10); 
var mon1  = parseInt(str1.substring(3,5),10);
var yr1   = parseInt(str1.substring(6,10),10); 
var dt2   = parseInt(str2.substring(0,2),10); 
var mon2  = parseInt(str2.substring(3,5),10); 
var yr2   = parseInt(str2.substring(6,10),10); 
var date1 = new Date(yr1, mon1, dt1); 
var date2 = new Date(yr2, mon2, dt2); 

if(date2 < date1)
{
   alert("To date cannot be greater than from date");
   return false; 
} 
else 
{ 
   alert("Submitting ...");
   document.form1.submit(); 
} 
于 2011-04-16T11:30:40.763 回答