How do I compare dates in javascript with two different formats?
function mainFunc() {
dueDate = "30/12/2014";
var firstReminderDate = dueDate;
var today = new Date();
var firstDate = convertToDate(firstReminderDate);
if (today > firstDate) {
//send reminder to A
} else {
// send reminder to B
}
}
function convertToDate(dateString) {
var dateData = dateString.split("/");
var date = new Date(new Date().setFullYear(dateData[0], dateData[1] - 1, dateData[2]));
return new Date(date);
}
I need to compare two dates, not times, and how do I remove the time part and just compare the dates? ConvertToDate () returns "Thu Jan 01 05:30:00 GMT + 05: 30 1970" every time?
source to share
You can simplify your code. To get the date from dd/mm/yyyy
by simply dividing by /
, changing the result and appending it to '/', you get yyyy/mm/dd
which is valid input for the new one Date
to compare with another Date
, See snippet
var report = document.querySelector('#result');
report.innerHTML += '30/12/2014 => '+ mainFunc('30/12/2014');
report.innerHTML += '<br>01/12/2014 => '+ mainFunc('01/01/2014');
function mainFunc(due) {
due = due ? convertToDate(due) : new Date;
return new Date > due
? due +' passed: <b>send reminder to A</b>'
: due +' not passed: <b>send reminder to B</b>';
}
function convertToDate(dateString) {
return new Date(dateString.split("/").reverse().join('/'));
}
<div id="result"></div>
source to share
Just return it in milliseconds
function convertToDate(dateString) {
var dateData = dateString.split("/");
return +new Date(new Date().setFullYear(dateData[0], dateData[1] - 1, dateData[2]));
}
And also change var today = new Date();
to var today = +new Date();
. This should work now. +
here converts the object Date
to milliseconds.
source to share
I recommend momentjs lib to parse, validate, manipulate and display dates in JavaScript.
var firstDate = moment("30/12/2014", "DD/MM/YYYY")
var today = moment();
// Format to Unix Timestamp to compare
if(today.format('X') > firstDate.format('X')){
//send reminder to A
}else{
// send reminder to B
}
Here is the link http://momentjs.com/
source to share