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
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-t12672js>t3 = new Date('2009 Jan 1')Thu Jan 01 2009 00:00:00 GMT-0500 (Eastern Standard Time)js>t1-t32470768442js>t1>t3true
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)
// Source: http://stackoverflow.com/questions/497790var 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);}}
/* 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));
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;}
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");}
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;}
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); // falseconsole.log('x > y', x > y); // falseconsole.log('x <= y', x <= y); // trueconsole.log('x >= y', x >= y); // trueconsole.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
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
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() ; //1375077000000console.log(typeof timeStamp_date_one);//numbervar timeStamp_date_two = new Date(date_two).getTime() ;//1375080600000console.log(typeof timeStamp_date_two);//number
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
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 Oracletform.START_DATE.value = estStartDate + " 00:00:00";}
if(tform.END_DATE.value!=""){var estEndDate = tform.END_DATE.value;//format for Oracletform.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;}}
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");}
<script type="text/javascript">function parseDate(input) {var datecomp= input.split('.'); //if date format 21.09.2017
var tparts=timecomp.split(':');//if time also givingreturn new Date(dparts[2], dparts[1]-1, dparts[0], tparts[0], tparts[1]);// here new date( year, month, date,)}</script>
<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 requirmentif(Date1 = Date2){return false; //or your code {}}});</script>
// 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.
例如,当前时间(大约是我开始键入这些单词的时间)是Fri Jan 31 2020 10:41:04 GMT-0600(中央标准时间),而客户输入他的出生日期为“01/31/2002”。
如果我们使用“365天/年”,即“31536000000”毫秒,我们将得到以下结果:
let currentTime = new Date();let customerTime = new Date(2002, 1, 31);let age = (currentTime.getTime() - customerTime.getTime()) / 31536000000console.log("age: ", age);