JavaScript Programming/Date and Time/Example Code
Appearance
example.html
[edit | edit source]<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Cache-Control" content="no-cache">
<title>Example</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
</style>
<script defer src="example.js"></script>
</head>
<body>
<noscript>Enable JavaScript to see web page content.</noscript>
<h1>Date and Time</h1>
<p>
<label for="date">Select a date:</label>
<input type="date" id="date"></input>
</p>
<p>
<label for="iso">ISO:</label>
<output id="iso"></output><br>
<label for="utc">UTC:</label>
<output id="utc"></output>
</p>
<p>
<label for="now">Now:</label>
<output id="now"></output>
</p>
<p>
<label for="code1">Code 1:</label>
<output id="code1"></output>
<button id="code1-button">Run</button><br>
<label for="code2">Code 2:</label>
<output id="code2"></output>
<button id="code2-button">Run</button><br>
</p>
</body>
</html>
example.js
[edit | edit source]// This program displays date and time methods.
//
// References:
// https://en.wikibooks.org/wiki/JavaScript
"use strict";
window.addEventListener("load", function () {
document.getElementById("date").addEventListener("change", inputChange);
window.setInterval(timerInterval, 1000);
document.getElementById("code1-button").addEventListener("click", code1Click);
document.getElementById("code2-button").addEventListener("click", code2Click);
});
function inputChange() {
let value = document.getElementById("date").value;
let date = new Date(value);
let iso = date.toISOString();
document.getElementById("iso").innerText = iso;
let utc = date.toUTCString();
document.getElementById("utc").innerText = utc;
}
function timerInterval() {
let now = Date.now();
document.getElementById("now").innerText = now +
" (milliseconds since January 1, 1970)";
}
function code1Click() {
let start = Date.now();
let result = "";
// loop one million times
for (let i = 0; i < 1000; i++) {
for (let j = 0; j < 1000; j++) {
result = i * j;
}
}
document.getElementById("code1").innerText = result;
let elapsed = Date.now() - start;
document.getElementById("code1").innerText = elapsed;
}
function code2Click() {
let start = Date.now();
// loop one million times
for (let i = 0; i < 1000; i++) {
for (let j = 0; j < 1000; j++) {
document.getElementById("code2").innerText = i * j;
}
}
let elapsed = Date.now() - start;
document.getElementById("code2").innerText = elapsed;
}