I've got a string from an input field which I use for date with a format like this 25-02-2013. Now I want to compare the string with today's date. I want to know if the string is older or newer then today's date.
Any suggestions?
To compare two dates, you can use either toString() or valueOf() . The toString() method converts the date into an ISO date string, and the valueOf() method converts the date into milliseconds since the epoch.
Call the getTime() method on each date to get a timestamp. Compare the timestamp of the dates. If a date's timestamp is greater than another's, then that date comes after.
In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.
<script type="text/javascript"> var q = new Date(); var m = q.getMonth()+1; var d = q.getDay(); var y = q.getFullYear(); var date = new Date(y,m,d); mydate=new Date('2011-04-11'); console.log(date); console.log(mydate) if(date>mydate) { alert("greater"); } else { alert("smaller") } </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With