I have been trying to work on the ability to customize the date and time as part of a larger project. Something like this:
<body>
<input type="date" id="date-input" placeholder="Date">
<input type="time" id="time-input" placeholder="Time">
<button onclick="setDateTime()">Set Date & Time</button>
<h1>Current Date & Time:</h1>
<span id="datetime-span"></span>
</body>
However, I am not sure on how I can not only display the values that I enter, but also make sure that the time entered will be updated every second/minute.
My current code looks like this:
function setDateTime() {
var dateInput = document.getElementById('date-input').value;
var timeInput = document.getElementById('time-input').value;
var datetimeSpan = document.getElementById('datetime-span');
var dateTime = dateInput + ' ' + timeInput;
datetimeSpan.textContent = dateTime;
// Update the time every minute
setInterval(updateDateTime, 60000);
}
function updateDateTime() {
var dateInput = document.getElementById('date-input').value;
var timeInput = document.getElementById('time-input').value;
var datetimeSpan = document.getElementById('datetime-span');
// What now?
}
UPDATE: Thanks to the help of Kiran Shahi, this problem is now solved. The Javascript is now as follows:
var runningHour;
var runningMinute;
var intervalId;
function setDateTime() {
var dateInput = document.getElementById('date-input').value;
var timeInput = document.getElementById('time-input').value;
var datetimeSpan = document.getElementById('datetime-span');
runningHour = timeInput.split(":")[0];
runningMinute = timeInput.split(":")[1];
var dateTime = dateInput + ' ' + timeInput;
datetimeSpan.textContent = dateTime;
clearInterval(intervalId);
// Update the time every second, for demo purposes
intervalId = setInterval(updateDateTime, 1000);
}
function updateDateTime() {
var dateInput = document.getElementById('date-input').value;
var timeInput = document.getElementById('time-input').value;
var datetimeSpan = document.getElementById('datetime-span');
if (runningMinute < 59) {
runningMinute++;
} else {
runningMinute = 00;
if (runningHour < 23) {
runningHour++;
} else {
runningHour = 00;
}
}
var paddedHour = runningHour.toString().padStart(2, '0');
var paddedMinute = runningMinute.toString().padStart(2, '0');
datetimeSpan.textContent = dateInput + ' ' + paddedHour + ':' + paddedMinute;
}
2
Answers
Here I have implemented a rough algorithm to update the time for every second. In your case you can change it into every minute. The basic idea here is to split the time base on
:
so that we get hours and minute. And increase the minute for every second/minute you want to until its 59 otherwise reset it to 00. Similarly, incase of hour increase it unit its 23 and reset to 00 if it is 23.I hope this solution provide you rough idea for your problem.
To customize the date input to show the user, you can use the following code as a template:
css:
I hope it helped you:)