timeadd / index.html
reonjy's picture
Update index.html
915e0ca verified
raw
history blame
2.23 kB
<!DOCTYPE html>
<html lang="en">
<center>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Time Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
}
input, button {
padding: 5px;
}
.new-time {
font-size: 24px;
background-color: yellow;
padding: 10px;
display: inline-block;
margin-top: 10px;
}
.title {
background-color: lightgreen;
display: inline-block;
padding: 5px;
}
</style>
</head>
<body>
<h1 class="title">Time Calculator</h1>
<p>Enter the initial time and the number of minutes to add:</p>
<label for="time">Time:</label>
<input type="time" id="time" value="03:45">
<label for="am_pm">AM/PM:</label>
<select id="am_pm">
<option value="am">AM</option>
<option value="pm">PM</option>
</select>
<br>
<label for="minutes">Minutes to add:</label>
<input type="number" id="minutes" value="20">
<br>
<button onclick="calculateNewTime()">Calculate New Time</button>
<p id="result"></p>
<script>
function calculateNewTime() {
const timeInput = document.getElementById("time").value;
const amPm = document.getElementById("am_pm").value;
const minutesToAdd = parseInt(document.getElementById("minutes").value);
let [hours, minutes] = timeInput.split(":").map(Number);
// Convert to 24-hour format
if (amPm === "pm" && hours !== 12) {
hours += 12;
} else if (amPm === "am" && hours === 12) {
hours = 0;
}
// Add the minutes
minutes += minutesToAdd;
// Handle minute overflow
if (minutes >= 60) {
hours += Math.floor(minutes / 60);
minutes = minutes % 60;
}
// Handle hour overflow
if (hours >= 24) {
hours = hours % 24;
}
// Convert back to 12-hour format
let newAmPm = "AM";
if (hours >= 12) {
newAmPm = "PM";
if (hours > 12) {
hours -= 12;
}
} else if (hours === 0) {
hours = 12;
}
const newTime = `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")} ${newAmPm}`;
document.getElementById("result").innerHTML = `<span class="new-time">New Time: ${newTime}</span>`;
}
</script>
</body>
</center>
</html>