I need to calculate the time passed between the first click on a start button and a second click on a finish button. I need it to be in the format h:m:s. And I need to save the time with PHP but don't know how.
CodePudding user response:
You can do something like this:
<button id="start">START</button>
<button id="end">END</button>
<script>
let startBtn = document.querySelector("#start")
let endBtn = document.querySelector("#end")
let startTimeStamp;
let result;
startBtn.onclick = (e) => {
startTimeStamp = e.timeStamp;
}
endBtn.onclick = (e) => {
result = e.timeStamp - startTimeStamp;
result = formatResult(result);
console.log(result)
sendResult(result);
}
function formatResult(ms) {
let seconds = Math.floor(ms / 1000);
let minutes = Math.floor(seconds / 60);
let hours = Math.floor(minutes / 60);
seconds = seconds % 60;
minutes = minutes % 60;
hours = hours.toString().length == 1 ? "0" hours : hours;
minutes = minutes.toString().length == 1 ? "0" minutes : minutes;
seconds = seconds.toString().length == 1 ? "0" seconds : seconds;
return `${hours}:${minutes}:${seconds}`;
}
function sendResult(result) {
let formData = new FormData()
formData.append("result", result)
fetch("index.php", { method: "POST", body: formData }).then(res => res.text().then(res => console.log(res)))
}
</script>
then in php:
<?php
$mysqli = mysqli_connect("localhost", "root", "", "db");
mysqli_query("INSERT INTO [table] values('$_POST[result]')");
?>