You can't use element.value
to get the contents of an arbitrary HTML element, .value
only works on form elements. Use element.innerHTML
instead:
var from_date = document.getElementById('from_date').innerHTML;
Also, your use of substring
is wrong. I think substr
is more clear:
var YYYY = from_date.substr(0,4);
var MM = from_date.substr(4,2);
var DD = from_date.substr(6,2);
In addOrSubtracDays
(shouldn't that be addOrSubtractDays
?) you want the number of milliseconds, so you should call Date.getTime
. Moreover, you actually want to return
the new value:
return new Date(jsCurDate.getTime() + daylength * daysOffset);
When changing #from_date
you probably want your date to be in the same format. For this, I extend Date
's prototype with a new method (and String
with a helper function):
String.prototype.padLeft = function (length, character) {
return new Array(length - this.length + 1).join(character || ' ') + this;
};
Date.prototype.toFormattedString = function () {
return [String(this.getFullYear()),
String(this.getMonth()+1).padLeft(2, '0'),
String(this.getDate()).padLeft(2, '0')].join('');
};
After this, we can simply call toFormattedString
:
document.getElementById('from_date').innerHTML = newDate.toFormattedString();
BTW, you don't need to explicitly convert YYYY
, MM
and DD
to integers with base 10; those are converted automatically (without assuming a string beginning with 0
is an octal number):
var jsCurDate = new Date(YYYY, MM - 1, DD);
For the sake of clarity, the complete script now reads:
String.prototype.padLeft = function (length, character) {
return new Array(length - this.length + 1).join(character || ' ') + this;
};
Date.prototype.toFormattedString = function () {
return [String(this.getFullYear()),
String(this.getMonth()+1).padLeft(2, '0'),
String(this.getDate()).padLeft(2, '0')].join('');
};
function date_move(direction){
var from_date = document.getElementById('from_date').innerHTML;
var YYYY = from_date.substr(0,4);
var MM = from_date.substr(4,2);
var DD = from_date.substr(6,2);
var jsCurDate = new Date(YYYY, MM - 1, DD);
var newDate = addOrSubtracDays(jsCurDate, direction);
document.getElementById('from_date').innerHTML = newDate.toFormattedString();
}
function addOrSubtracDays(jsCurDate, daysOffset){
var daylength= 1*24*60*60*1000;
return new Date(jsCurDate.getTime() + daylength * daysOffset);
}
date_move(+1);