Skip to content

Instantly share code, notes, and snippets.

@dewey4iv
Last active February 26, 2018 04:43
Show Gist options
  • Save dewey4iv/9db47003717a8f1a0bd19839fb8602b2 to your computer and use it in GitHub Desktop.
Save dewey4iv/9db47003717a8f1a0bd19839fb8602b2 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pick A Day</title>
</head>
<body>
<h1>Compute Date</h1>
<div class="output">
Then: <span class="then"></span><br/><br/>
Days: <span class="days">0</span>
Months: <span class="months">0</span>
Years: <span class="years">0</span>
</div>
<form id="input">
<label for="day">Day(s)</label>
<input type="text" name="day" value="28"><br/>
<label for="month">Month(s)</label>
<input type="text" name="month" value="02"><br/>
<label for="year">Year(s)</label>
<input type="text" name="year" value="2018"><br/>
<input type="submit" value="Compute">
</form>
</body>
<script type="text/javascript">
function handleSubmit() {
const thenOut = document.querySelector('.output .then')
const days = document.querySelector('.output .days')
const months = document.querySelector('.output .months')
const years = document.querySelector('.output .years')
const monthInput = document.querySelector("input[name='month']")
const dayInput = document.querySelector("input[name='day']")
const yearInput = document.querySelector("input[name='year']")
let month = parseInt(monthInput.value)
let day = parseInt(dayInput.value)
let year = parseInt(yearInput.value)
if (day > 31) {
let remainder = day % 31
month += (day - remainder) / 31
day = remainder
}
if (month > 12) {
let remainer = month % 12
year += (month - remainer) / 12
month = remainer
}
const then = new Date(year, (month-1), day) // months start at -0- [because JS is weird]
const now = new Date()
thenOut.innerHTML = then
const output = computeFromRaw((then - now))
days.innerHTML = output.days
months.innerHTML = output.months
years.innerHTML = output.years
}
const aYear = 1000 * 60 * 60 * 24 * 365
const aMonth = 1000 * 60 * 60 * 24 * 31
const aDay = 1000 * 60 * 60 *24
function computeFromRaw(raw) {
const years = Math.floor(raw/aYear)
raw -= years * aYear
const months = Math.floor(raw/aMonth)
raw -= months * aMonth
const days = Math.floor(raw/aDay)
return {
years,
months,
days
}
}
// register event
const form = document.getElementById('input')
form.addEventListener('submit', e => {
e.preventDefault()
handleSubmit()
})
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment