-2

I have a page and user can never close it. In text field i have current date.
enter image description here

I need to update this date every day. But how to calculate and update this value at start of new day.

Arti
  • 7,356
  • 12
  • 57
  • 122

2 Answers2

0

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).

Community
  • 1
  • 1
Anthony Blackshaw
  • 2,549
  • 2
  • 16
  • 20
  • Why it matters if they update the field? ... A second later the timer will alter it back to today's date anyway – Asons Jan 10 '16 at 13:12
  • @LGSon my assumption is if they update the field they will next submit the form (either by hitting enter or by clicking the *Get stats* button. So when the user is focused on the field we don't want the value of the field changed by the update function as they may wish to submit a different value than the current date (equally the setInterval could just be updated to be per minute to reduce the likelihood of such a collision). – Anthony Blackshaw Jan 10 '16 at 13:44
0

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.

Asons
  • 84,923
  • 12
  • 110
  • 165