Suppose I receive two dates from the datepicker plugin in format DD/MM/YYYY
var date1 = '25/02/1985'; /*february 25th*/
var date2 = '26/02/1985'; /*february 26th*/
/*this dates are results form datepicker*/
if(process(date2) > process(date1)){
alert(date2 + 'is later than ' + date1);
}
What should this function look like?
function process(date){
var date;
// Do something
return date;
}
To handle equality comparison, we use the date object alongside the getTime() date method which returns the number of milliseconds. But if we want to compare specific information like day, month, and so on, we can use other date methods like the getDate() , getHours() , getDay() , getMonth() and getYear() .
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.
To compare two date strings:Pass the strings to the Date() constructor to create 2 Date objects. Compare the output from calling the getTime() method on the dates.
Split on the "/" and use the Date constructor.
function process(date){
var parts = date.split("/");
return new Date(parts[2], parts[1] - 1, parts[0]);
}
It could be more easier:
var date1 = '25/02/1985'; /*february 25th*/
var date2 = '26/02/1985'; /*february 26th*/
if ($.datepicker.parseDate('dd/mm/yy', date2) > $.datepicker.parseDate('dd/mm/yy', date1)) {
alert(date2 + 'is later than ' + date1);
}
For more details check this out. Thanks.
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