简体   繁体   中英

how to compare date with todays date ? where date is in format dd-mm-yyyy?

how to compare date with the today's date where date is in format dd-mm-yyyy

var sdate = document.getElementById('datepicker-example2').value;
if (Date.parse(document.getElementById("datepicker-example2").value) < Date.parse(dateToday.getDate() + "/" + dateToday.getmonth() + "/" + dateToday.getYear())) {
    alert("dsd");
}

Use Date.now()

var sdate = document.getElementById('datepicker-example2').value;
if (Date.parse(sdate) < Date.now()) {
    alert("dsd");
}

Also I dont see why you retrieve the datepickers value second time while you have stored it in the first place. Its better to use the stored one.

date = new Date()

is today's date. Use the different methods of the javascript date objects to collect the month, day, and year from today and the date you are comparing,

http://www.comptechdoc.org/independent/web/cgi/javamanual/javadate.html

getMonth ( date ) + "-" + getDay ( date ) + "-" + getYear ( date )

That point you in the right direction.

Not super accurate but this will get you time difference in days between two dates. Invert the operands for future dates. Of course the time conversion could be better but you get the idea:

var today = new Date();
var date = new Date('10/23/12')
var diff = ~~(((today.getTime() - date.getTime()) * 2.76e-7) / 24);
var currentDate = Date.now();
if (currentDate > date2.getTime()) {
    alert("The current date is after the second date!");
}

The now() method returns the milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now as a number.

The getTime() returns the Milliseconds since midnight January 1, 1970

Working Demo

Parse your date :

   var m = date.match (/(\d\d)-(\d\d)-(\d\d\d\d)/);

Create a new date object for that date :

   if (m) {// check if date was matched  
     m = new Date (+m[3], +m[2] - 1, +m[1]);

And compare with todays date :

     if ((new Date ()).getTime () < m.getTime ()) {
       ...
     }
   } else { // Bad date format

   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM