I have a page and user can never close it. In text field i have current date.
I need to update this date every day. But how to calculate and update this value at start of new day.
I have a page and user can never close it. In text field i have current date.
I need to update this date every day. But how to calculate and update this value at start of new day.
If you are happy to rely on the browser to provide the date/time then you could use setInterval
to check the browser's current date against the date in the input
field frequently and update it whenever they don't match, for example:
updateDateField = function () {
// Get the field we want to set the date for
var field = document.getElementById('today');
// Check if the field has focus, if it does then the user may be changing it
// so don't perform the update.
if (field == document.activeElement) {
return;
}
// Get the current date
var now = new Date();
// Format the date to YYYY-MM-DD
var yyyy = now.getFullYear().toString();
var mm = (now.getMonth() + 1).toString();
var dd = now.getDate().toString();
var nowStr = [
yyyy,
(mm[1] ? mm : "0" + mm[0]),
(dd[1] ? dd : "0" + dd[0])
].join('-');
// Check if the field value and current date are different
if (field.value != nowStr) {
field.value = nowStr;
}
}
// Check (and update if required) the date field every second
setInterval(updateDateField, 1000);
(The code for formatting the date came from the SO post Get String in YYYYMMDD format from JS date object?).
In my example you'd need to change the code to use the Id of your input
.
UPDATE: I changed my code so that it doesn't update the date if the input
field has focus (otherwise we might change it while they are updating the field).
The simplest way would be to run this at page load
setInterval(function (){
document.getElementById('today').value = (new Date()).toISOString().slice(0,10));
}, 60000);
This runs every minute and update the date field, and if you need to update it more often or seldom, just change the interval time.
If you need the servers date, add an ajax call to get its date.