I'm trying to get a date difference between a date and today with JS. Here is my code, but I get "a.getFullYear is not a function".
var brbr = '<br><br>';
var duedate="2015-11-06";
document.write(duedate);
document.write(brbr);
// Today's date:
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = yyyy+'-'+mm+'-'+dd;
document.write(today);
document.write(brbr);
// DIFFERENCE 2 dates:
var _MS_PER_DAY = 1000 * 60 * 60 * 24;
// a and b are javascript Date objects
function dateDiffInDays(a, b) {
// Discard the time and time-zone information.
var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
Result:
var days_left = dateDiffInDays(today, duedate);
document.write(days_left);
document.write(brbr);
I'm trying to get a date difference between a date and today with JS. Here is my code, but I get "a.getFullYear is not a function".
var brbr = '<br><br>';
var duedate="2015-11-06";
document.write(duedate);
document.write(brbr);
// Today's date:
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = yyyy+'-'+mm+'-'+dd;
document.write(today);
document.write(brbr);
// DIFFERENCE 2 dates:
var _MS_PER_DAY = 1000 * 60 * 60 * 24;
// a and b are javascript Date objects
function dateDiffInDays(a, b) {
// Discard the time and time-zone information.
var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
Result:
var days_left = dateDiffInDays(today, duedate);
document.write(days_left);
document.write(brbr);
Share
Improve this question
edited Nov 4, 2015 at 1:09
Lee Taylor
7,98416 gold badges37 silver badges53 bronze badges
asked Nov 4, 2015 at 1:06
mesqueebmesqueeb
6,3847 gold badges52 silver badges85 bronze badges
2 Answers
Reset to default 2You need to convert today
and duedate
into Date()
objects in order to use .getFullYear()
function dateDiffInDays(a, b) {
var aDate = new Date(a);
var bDate = new Date(b);
// Discard the time and time-zone information.
var utc1 = Date.UTC(aDate.getFullYear(), aDate.getMonth(), aDate.getDate());
var utc2 = Date.UTC(bDate.getFullYear(), bDate.getMonth(), bDate.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
What I did was:
var a = Date.parse("date");
var b = new Date(a);