Porównaj dwie daty Z JavaScript
Czy ktoś może zasugerować sposób na porównanie wartości dwóch dat większych niż, mniejszych niż, a nie w przeszłości za pomocą JavaScript? Wartości będą pochodzić z pól tekstowych...
30 answers
Obiekt Date zrobi to, co chcesz-zbuduj po jednym dla każdej daty, a następnie porównaj je za pomocą >
, <
, <=
lub >=
.
The ==
, !=
, ===
, i !==
operatory wymagają użycia date.getTime()
jak w
var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();
Aby było jasne, samo sprawdzanie równości bezpośrednio z obiektami danych nie będzie działać
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)
Sugeruję użycie rozwijanych lub podobnych ograniczonych form wprowadzania daty, a nie pól tekstowych, aby nie znaleźć się w walidacja danych wejściowych.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-26 16:46:33
Najprostszym sposobem porównywania dat w javascript jest najpierw przekonwertowanie go do obiektu Date, a następnie porównanie tych obiektów date.
Poniżej znajduje się obiekt o trzech funkcjach:
-
Daty.compare (A, b)
Zwraca liczbę:
- -1 jeśli A
- 0 if a = b
- 1 if a > b
- NaN Jeśli a lub b jest nielegalną datą
-
Daty.inRange (d, start,end)
Zwraca wartość logiczną lub NaN:
- true if d is between the start and end (inclusive)
- false if d is before start or after end . NaN, jeśli jedna lub więcej dat jest niezgodna z prawem.
Daty.convert
Używane przez inne funkcje do konwersji danych wejściowych na obiekt daty. Wejście Może być
- a date - obiekt: wejście jest zwracane jako jest.
- an array : interpretowane jako [Rok, Miesiąc,Dzień]. Uwaga miesiąc to 0-11.
- A liczba : interpretowana jako liczba milisekund od 1 stycznia 1970 (znacznik czasu)
- A string : obsługiwane jest kilka różnych formatów ,takich jak" YYYY/MM/DD"," MM/DD/YYYY"," Jan 31 2009 " itp.
- an obiekt : interpretowany jako obiekt z atrybutami roku, miesiąca i daty. Uwaga miesiąc to 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
);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-01 17:16:31
Porównaj <
i >
Jak zwykle, ale wszystko, co dotyczy =
powinno używać prefiksu +
. Tak:
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 <= +y; => true
+x >= +y; => true
+x === +y; => true
Mam nadzieję, że to pomoże!Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-23 12:21:09
Operatory relacyjne <
<=
>
>=
może być używany do porównywania dat 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
Jednak operatory równości ==
!=
===
!==
nie można użyć do porównania (wartości) dat , ponieważ :
- dwa różne obiekty nigdy nie są sobie równe dla ścisłych lub abstrakcyjnych porównań.
- wyrażenie porównujące Obiekty jest prawdziwe tylko wtedy, gdy operandy odwołują się do tego samego obiektu.
Możesz porównać wartość dat dla równości przy użyciu dowolnej z tych metod:
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
Obie Date.getTime()
i Date.valueOf()
zwracają liczbę milisekund od 1 stycznia 1970, 00: 00 UTC. Zarówno funkcja Number
, jak i operator uniary +
wywołują metody valueOf()
Za kulisami.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-31 17:08:37
Zdecydowanie najprostszą metodą jest odjęcie jednej daty od drugiej i porównanie wyniku.
var oDateOne = new Date();
var oDateTwo = new Date();
alert(oDateOne - oDateTwo === 0);
alert(oDateOne - oDateTwo < 0);
alert(oDateOne - oDateTwo > 0);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-01 00:48:12
Porównywanie dat W JavaScript jest dość proste... JavaScript ma wbudowany system porównywania dla dat , co sprawia, że porównanie jest tak łatwe...
Po prostu wykonaj następujące kroki w celu porównania wartości 2 dat, na przykład masz 2 wejścia, z których każdy ma wartość daty w String
i możesz je porównać...
1. masz 2 wartości łańcuchowe, które otrzymujesz z wejścia i chcesz je porównać, są one jak poniżej:
var date1 = '01/12/2018';
var date2 = '12/12/2018';
2. muszą być Date Object
aby być porównane jako wartości daty, więc po prostu przekonwertuj je na datę, używając new Date()
, po prostu przypisuję je dla uproszczenia wyjaśnienia, ale możesz to zrobić tak, jak chcesz:
date1 = new Date(date1);
date2 = new Date(date2);
3. Teraz wystarczy je porównać, używając >
<
>=
<=
date1 > date2; //false
date1 < date2; //true
date1 >= date2; //false
date1 <= date2; //true
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-07 10:38:19
Porównaj tylko dzień (ignorując Składnik czasu):
Date.prototype.sameDay = function(d) {
return this.getFullYear() === d.getFullYear()
&& this.getDate() === d.getDate()
&& this.getMonth() === d.getMonth();
}
Użycie:
if(date1.sameDay(date2)) {
// highlight day on calendar or something else clever
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-14 15:37:57
Jaki format?
Jeśli zbudujesz obiekt Javascript Date , możesz po prostu odjąć je, aby uzyskać różnicę milisekund (edit: lub po prostu porównać je):
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-20 16:14:32
KRÓTKA ODPOWIEDŹ
Oto funkcja, która zwraca {boolean} jeśli z dateTime > do dateTime Demo w akcji
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
Explanation
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
Ponieważ masz teraz obie datetime w number type można je porównać z dowolnymi operacjami porównawczymi
( >, = I
Then
Jeśli znasz C#
Niestandardowy format daty i czasu to biblioteka powinna zrobić dokładnie to samo i pomóc w sformatowaniu daty i godziny dtmFRM niezależnie od tego, czy przekazujesz w formacie date time string, czy unix
Użycie
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
Wystarczy przesłać dowolny z tych formatów do biblioteki js
Plik
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-27 19:22:36
function datesEqual(a, b)
{
return (!(a>b || b>a))
}
Używasz tego kodu,
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");
}
A także sprawdź ten link http://www.w3schools.com/js/js_obj_date.asp
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-17 04:06:02
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-28 07:18:31
Aby dodać jeszcze jedną możliwość do wielu istniejących opcji, możesz spróbować:
if (date1.valueOf()==date2.valueOf()) .....
...co mi pasuje. Oczywiście musisz upewnić się, że obie daty nie są niezdefiniowane...
if ((date1?date1.valueOf():0)==(date2?date2.valueOf():0) .....
W ten sposób możemy zapewnić pozytywne porównanie, jeśli oba są również niezdefiniowane, lub...
if ((date1?date1.valueOf():0)==(date2?date2.valueOf():-1) .....
...jeśli wolisz, żeby nie byli równi.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-26 15:41:05
Uwaga-Porównaj Tylko Część Daty:
Gdy porównamy dwie daty w javascript. Bierze to również pod uwagę godziny, minuty i sekundy.. Jeśli więc musimy tylko porównać datę, to jest to podejście:
var date1= new Date("01/01/2014").setHours(0,0,0,0);
var date2= new Date("01/01/2014").setHours(0,0,0,0);
Teraz: if date1.valueOf()> date2.valueOf()
będzie działać jak urok.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-15 14:41:06
Przez 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"));
Metoda zwraca 1, Jeśli dateTimeA
jest większa niż dateTimeB
Metoda zwraca 0 Jeżeli dateTimeA
jest równa dateTimeB
Metoda zwraca -1 jeżeli dateTimeA
jest mniejsza niż dateTimeB
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-11 15:47:09
Aby porównać dwie daty możemy użyć daty.biblioteka JavaScript JS, którą można znaleźć pod adresem: https://code.google.com/archive/p/datejs/downloads
I użyj metody Date.compare( Date date1, Date date2 )
i zwróci liczbę , która oznacza następujący wynik:
-1 = date1 jest mniejsza od date2.
0 = wartości są równe.
1 = date1 jest większa niż date2.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-31 17:18:59
Aby utworzyć daty z wolnego tekstu w Javascript należy je przetworzyć do obiektu Date ().
Przydałaby Ci się Randka.parse (), która zajmuje wolny tekst próbuje przekonwertować go na nową datę, ale jeśli masz kontrolę nad stroną, zalecałbym użycie HTML select boxes zamiast tego lub selektora daty, takiego jak Yui calendar control lub jQuery UI Datepicker .
Gdy masz datę, jak zauważyli inni, możesz użyć prostej arytmetyki, aby odjąć daty i przekształcić ją z powrotem na liczbę dni, dzieląc liczbę (w sekundach) przez liczbę sekund w ciągu dnia (60*60*24 = 86400).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-01-29 19:35:19
Powiedzmy, że masz obiekty daty A i B, uzyskaj ich wartość czasu EPOC, a następnie odjmij, aby uzyskać różnicę w milisekundach.
var diff = +A - +B;
To wszystko.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-23 03:03:35
Odejmij dwie daty Uzyskaj różnicę w milisekundzie, jeśli otrzymasz 0
to ta sama data
function areSameDate(d1, d2){
return d1 - d2 === 0
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-09 13:25:24
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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-27 20:42:55
Ulepszona wersja kodu zamieszczonego przez "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
);
};
Użycie:
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));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-20 04:02:04
Jeśli poniżej znajduje się twój format daty, Możesz użyć tego kodu:
var first = '2012-11-21';
var second = '2012-11-03';
if(parseInt(first.replace(/-/g,""),10) > parseInt(second.replace(/-/g,""),10)){
//...
}
Sprawdzi czy liczba 20121121
jest większa od 20121103
czy nie.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-23 14:15:20
Zazwyczaj przechowuję Dates
jako timestamps(Number)
w bazach danych.
Kiedy muszę porównać, po prostu porównuję pomiędzy tymi znacznikami czasu lub
Przekonwertować go do obiektu Date, a następnie porównać z > <
w razie potrzeby.
Zauważ, że = = lub = = = nie działa poprawnie, chyba że Twoje zmienne są referencjami tego samego obiektu Date.
Konwertuj najpierw te obiekty daty na znacznik czasu (numer), a następnie porównaj ich równość.
Data do 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);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-22 01:40:14
UWAGA NA STREFĘ CZASOWĄ
Data javascript nie ma pojęcia strefy czasowej. Jest to moment w czasie (kleszcze od epoki) z przydatnymi funkcjami do tłumaczenia łańcuchów w "lokalnej" strefie czasowej. Jeśli chcesz pracować z datami przy użyciu obiektów daty, tak jak wszyscy tutaj robią, chcesz, aby daty reprezentowały północ UTC na początku danej daty. jest to wspólna i niezbędna konwencja, która pozwala pracować z datami niezależnie od sezon lub Strefa czasowa ich powstania. Dlatego musisz być bardzo czujny, aby zarządzać pojęciem strefy czasowej, szczególnie podczas tworzenia obiektu daty o północy UTC.
Przez większość czasu będziesz chciał, aby Data odzwierciedlała strefę czasową użytkownika. Kliknij jeśli dziś są Twoje urodziny. Użytkownicy w NZ i USA klikają w tym samym czasie i otrzymują różne daty. W takim razie zrób to...
// 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()));
Czasami międzynarodowa porównywalność przewyższa lokalną dokładność. W takim razie do to...
// the date in London of a moment in time. Device timezone is ignored.
new Date(Date.UTC(myDate.getUTCYear(), myDate.getyUTCMonth(), myDate.getUTCDate()));
Teraz możesz bezpośrednio porównać swoje obiekty daty, jak sugerują inne odpowiedzi.
Po zadbaniu o zarządzanie strefą czasową podczas tworzenia, musisz również upewnić się, że strefa czasowa jest wyłączona podczas konwersji z powrotem do reprezentacji łańcuchowej. więc można bezpiecznie używać...
toISOString()
getUTCxxx()
getTime() //returns a number with no time or timezone.
.toLocaleDateString("fr",{timezone:"UTC"}) // whatever locale you want, but ALWAYS UTC.
I całkowicie unikać wszystkiego innego, zwłaszcza...
-
getYear()
,getMonth()
,getDate()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-20 09:51:47
Przed porównaniem obiektu Dates
spróbuj ustawić obie milisekundy na zero, tak jak Date.setMilliseconds(0);
.
W niektórych przypadkach, gdy obiekt Date
jest dynamicznie tworzony w javascript, jeśli nadal będziesz drukować Date.getTime()
, zobaczysz zmiany milisekund, co uniemożliwi równość obu dat.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-24 17:34:25
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;
}
Użyj tego kodu, aby porównać datę za pomocą javascript.
Dzięki D. Jeeva
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-10 10:20:12
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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-12 10:55:19
Oto co zrobiłem w jednym z moich projektów,
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;
}
}
Wywołanie tego na formularzu onsubmit. mam nadzieję, że to pomoże.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-20 15:37:31
Załóżmy, że masz do czynienia z tym 2014[:-/.]06[:-/.]06
lub tym 06[:-/.]06[:-/.]2014
formatem daty, wtedy możesz porównać daty w ten sposób
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
Jak widać, rozbieramy separator(y), a następnie porównujemy liczby całkowite.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-23 22:22:18
Witam Oto Mój kod do porównywania dat . W moim przypadku robię czek, aby nie pozwolić, aby wybrać poprzednie daty.
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;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-08 13:45:34