programing

JavaScript와 두 날짜 비교

sourcejob 2022. 12. 3. 00:33
반응형

JavaScript와 두 날짜 비교

JavaScript를 사용하여 과거보다 크거나 작거나 하지 않은 두 날짜의 을 비교할 수 있는 방법을 제안할 수 있습니까?값은 텍스트 상자에서 가져옵니다.

날짜 개체는 원하는 작업을 수행합니다. 각 날짜에 대해 하나씩 구성한 다음>,<,<= ★★★★★★★★★★★★★★★★★」>=.

==,!=,=== , , , , 입니다.!==는 반드시 합니다.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)

입력 확인 지옥이 되지 않도록 텍스트 상자 대신 드롭다운 또는 이와 유사한 형식의 날짜 입력을 사용하는 것이 좋습니다.


궁금한 문서:

1970년 1월 1일 00:00:00 UTC 이후 지정한 날짜의 수치를 밀리초 단위로 반환합니다(음수 값은 이전 시간에 대해 반환됩니다).

javascript에서 날짜를 비교하는 가장 쉬운 방법은 먼저 날짜를 날짜 개체로 변환한 다음 이러한 날짜 개체를 비교하는 것입니다.

다음 세 가지 기능을 가진 개체를 찾을 수 있습니다.

  • dates.details(a, b)

    숫자를 반환합니다.

    • -1(a < b의 경우
    • a = b인 경우 0
    • 1 if a > b
    • a 또는 b가 부정한 날짜일 경우 NaN
  • dates.inRange(d, start, end)

    부울 또는 NaN을 반환합니다.

    • d시작과 종료 사이에 있는 경우 true(실행)
    • d가 시작 전 또는 종료 후일 경우 false입니다.
    • 하나 이상의 날짜가 불법일 경우 NaN.
  • dates.details.details를 참조해 주세요.

    다른 함수가 입력을 날짜 개체로 변환하기 위해 사용합니다.입력은 다음과 같습니다.

    • a date-object : 입력이 그대로 반환됩니다.
    • 배열:[year, month, day]로 해석됩니다.참고 월은 0-11입니다.
    • a number : 1970년1월 1일 이후 밀리초로 해석됩니다(타임스탬프).
    • 문자열 : "YYY/MM/DD", "MM/DD/YY", "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<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
        );
    }
}

< ★★★★★★★★★★★★★★★★★」>여느 때처럼, 하지만 어떤 것이든== ★★★★★★★★★★★★★★★★★」=== 써야 요.+프레픽스다음과 같이 합니다.

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

연산자 " " "< <= > >=날짜 할 수 .JavaScript 날짜 비교는 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

, 등호연산자는== != === !==다음 이유로 날짜(값)를 비교할 수 없습니다.

  • 엄밀한 비교나 추상적인 비교에서는 두 개의 구별되는 객체가 결코 동일하지 않습니다.
  • 오브젝트를 비교하는 표현은 오퍼랜드가 같은 오브젝트를 참조하는 경우에만 true입니다.

다음 방법 중 하나를 사용하여 동일 날짜 값을 비교할 수 있습니다.

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.valueOf()1970년 1월 1일 00:00 UTC 이후의 밀리초수를 반환합니다. 다.Number and ary 。+가 ""를 호출합니다.valueOf()이면 수법

단연코 가장 쉬운 방법은 한 날짜를 다른 날짜에서 빼서 결과를 비교하는 것이다.

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

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

JavaScript에서 날짜를 비교하는 은 매우 쉽습니다.JavaScript에는 날짜 비교 시스템이 내장되어 있어 비교가 매우 용이합니다.

값을 는 다음 . , . 예를 들어 각각 날짜 값이 다음 위치에 있는 입력이 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 날짜 비교

날짜만 비교(시간 구성 요소 무시):

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

N.B. 시간대별로 년/월/일이 반환됩니다. 같은 날짜에 다른 시간대에서 두 날짜가 있는지 확인하려면 시간대 인식 라이브러리를 사용하는 것이 좋습니다.

예.

> (new Date('Jan 15 2021 01:39:53 Z')).getDate()  // Jan 15 in UTC
14  // Returns "14" because I'm in GMT-08

어떤 형식입니까?

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

메모 - 날짜만 비교 부품:

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()네, 네, 네.

간단한 방법은,

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

if (new Date(first) > new Date(second) {
    .....
}

단답

from dateTime > to dateTime Demo가 동작할 경우 {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

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 

현재 두 datetime을 모두 숫자 유형으로 가지고 있으므로 모든 비교 연산과 비교할 수 있습니다.

( > , < , = , != , = , !== , > = 및 <=

그리고나서

알고 계시다면C#커스텀 날짜 및 시각 형식 문자열 이 라이브러리는 동일한 작업을 수행하여 날짜 시간 문자열 또는 unix 형식으로 전달하는지 여부에 관계없이 날짜와 시각 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 파일

이 코드를 사용하면

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

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

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

는 1을 반환하면 1을 1로 하면 합니다.dateTimeA dateTimeB

는 0이면 합니다.dateTimeA는 「」와 같습니다.dateTimeB

메서드는 -1이면 을 반환합니다.dateTimeAdateTimeB

시간대 주의

Javascript 날짜에는 표준 시간대가 없습니다.이것은, 「로컬」타임 존내의 문자열과 변환하기 위한 편리한 기능을 갖춘 모멘트 인 타임(에폭 이래의 틱)입니다.여기 있는 모든 사람이 사용하는 것처럼 날짜 개체를 사용하여 날짜를 작업하려면 해당 날짜의 시작 부분에 UTC 자정을 표시해야 합니다.이는 작성 시기나 시간대에 관계없이 날짜를 작업할 수 있도록 하는 일반적인 필수 규칙입니다.따라서 특히 자정 UTC 날짜 개체를 작성할 때 시간대 개념을 관리하려면 매우 주의해야 합니다.

대부분의 경우, 당신은 사용자의 시간대를 반영하기 위해 당신의 날짜를 원할 것입니다.오늘이 생일인 경우 클릭합니다.NZ와 미국의 사용자는 동시에 클릭하여 다른 날짜를 얻을 수 있습니다.그럼 이렇게...

// 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()

많은 기존 옵션에 다른 가능성을 더하기 위해 다음을 시도할 수 있습니다.

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

나한테는 효과가 있는 것 같아.물론 두 날짜가 정의되어 있지 않은지 확인해야 합니다.

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

이렇게 하면 둘 다 정의되지 않은 경우에도 양수 비교를 할 수 있습니다.

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

그들이 동등하지 않기를 바란다면요

단위로 .0 날짜다

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

날짜 객체 A와 B를 얻었다고 가정하고 EPOC 시간 값을 얻은 다음 빼서 차이(밀리초)를 구합니다.

var diff = +A - +B;

그게 다예요.

날짜 형식이 다음과 같으면 다음 코드를 사용할 수 있습니다.

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

확인하겠습니다.2012112120121103그렇지 않으면.

두 날짜를 비교하려면 date.http://https://code.google.com/archive/p/datejs/downloads에 있는 JavaScript 라이브러리를 사용합니다.

를 사용합니다.Date.compare( Date date1, Date date2 )method는 다음 결과를 나타내는 번호를 반환합니다.

-1 = date1은 lessthan date2입니다.

0 = 값이 같습니다.

1 = date1이 date2보다 큽니다.

Javascript의 프리 텍스트에서 날짜를 작성하려면 Date() 오브젝트로 해석해야 합니다.

무료 텍스트를 사용하는 Date.parse()를 사용하면 새로운 날짜로 변환할 수 있지만 페이지를 제어할 수 있다면 HTML 선택 상자 또는 YUI 달력 컨트롤이나 jQuery UI Datepicker 등의 달력 선택기를 사용할 것을 권장합니다.

다른 사람이 지적한 대로 날짜가 있으면 간단한 계산을 사용하여 날짜를 뺀 후 숫자(초 단위)를 하루 동안의 초(60*60*24 = 86400)로 나누어 일수로 변환할 수 있습니다.

성능

현재 2020.02.27 MacOS High Sierra v10.13.6에서 Chrome v80.0, Safari v13.0.5 및 Firefox 73.0.1에서 선택한 솔루션의 테스트를 수행합니다.

결론들

  • ★★★d1==d2 (D) (D) 및 andd1===d2 (E) (E) are fastest for all browsers(E)는 모든 브라우저에서 가장 빠릅니다.
  • solution 해결 방법getTime (A) (A)보다 빠르다valueOf (B) (B) (B) (B) (B) (B))) (B) (B)) (B)) (B)) (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>

크롬 결과

여기에 이미지 설명 입력

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

'일부'가 게시한 코드 개량판

/* 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));

I usually store 나는 보통 저장한다.Dates as ~하듯이timestamps(Number)데이터베이스에 있습니다.이치노

비교할 필요가 있을 때는 타임스탬프나 타임스탬프만 비교만 하면 됩니다.

하여 짜짜 with와 > <필요하면.

== 또는 ===는 변수가 동일한 날짜 개체의 참조가 아니면 제대로 작동하지 않습니다.

먼저 이러한 날짜 개체를 타임스탬프(숫자)로 변환한 다음 동일한 날짜 개체를 비교합니다.


날짜에서 타임스탬프

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

비교하기 전에Dates오브젝트, 양쪽 밀리초를 0으로 설정합니다.Date.setMilliseconds(0);.

경우에 따라서는Date오브젝트는 javascript에서 동적으로 생성됩니다.Date.getTime()밀리초가 변경되므로 두 날짜가 동일하지 않습니다.

이 질문에 대한 나의 간단한 답변은

checkDisabled(date) {
    const today = new Date()
    const newDate = new Date(date._d)
    if (today.getTime() > newDate.getTime()) {
        return true
    }
    return false
}
       

이 이 문제를 있다고 해 보겠습니다.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

보시다시피 분리기를 제거하고 정수를 비교합니다.

        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를 사용하여 날짜를 비교할 때 사용합니다.

감사합니다.지바

언급URL : https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript

반응형