I'm trying to a make a live clock using JS Date();
It seems freeze, until, I refresh the page.
var today = new Date();
var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date;
setInterval(function() {
document.getElementById('clock1').innerHTML = dateTime;
document.getElementById('clock2').innerHTML = dateTime;
document.getElementById('clock3').innerHTML = dateTime;
document.getElementById('clock4').innerHTML = dateTime;
document.getElementById('clock5').innerHTML = dateTime;
}, 1000)
var span = document.getElementsByClassName('time');
function time() {
var d = new Date();
var s = d.getSeconds();
var m = d.getMinutes();
var h = d.getHours();
span.textContent = h + ":" + m + ":" + s;
}
setInterval(time, 1000);
#font-face {
font-family: "DOTMBold";
src: url("DOTMBold.TTF");
}
#font-face {
font-family: "LLPIXEL3";
src: url("LLPIXEL3.ttf");
}
#font-face {
font-family: "Technology";
src: url("Technology.ttf");
}
#font-face {
font-family: "The Led Display St";
src: url("The Led Display St.ttf");
}
#clock1 {
font-family: "Calculator";
font-size: 70px;
}
#clock2 {
font-family: "DOTMBold";
font-size: 70px;
}
#clock3 {
font-family: "LLPIXEL3";
font-size: 70px;
}
#clock4 {
font-family: "Technology";
font-size: 70px;
}
#clock5 {
font-family: "The Led Display St";
font-size: 70px;
}
<title>hw18</title>
<div id="clock1"><span class="time"></span></div>
<div id="clock2"><span class="time"></span></div>
<div id="clock3"><span class="time"></span></div>
<div id="clock4"><span class="time"></span></div>
<div id="clock5"><span class="time"></span></div>
Several issues
document.getElementsByClassName('time'); is plural. It returns a collection. You need to loop over the span - but the spans are gone when you change the clockX innerHTML
You do not add the time to the dateTime
You likely want to pad the digits
You need to make a new date object for every call.
You likely want to do the following:
extract the time into its own function
pad the digits
now the spans are no longer needed but can be reinstated if necessary
const pad = num => ("0" + num).slice(-2)
const getTime = function() {
var today = new Date();
return `${today.getFullYear()}-${pad(today.getMonth() + 1)}-${pad(today.getDate())}
${pad(today.getHours())}:${pad(today.getMinutes())}:${pad(today.getSeconds())}`;
}
setInterval(function() {
var dateTime = getTime()
document.getElementById('clock1').innerHTML = dateTime;
document.getElementById('clock2').innerHTML = dateTime;
document.getElementById('clock3').innerHTML = dateTime;
document.getElementById('clock4').innerHTML = dateTime;
document.getElementById('clock5').innerHTML = dateTime;
}, 1000)
#font-face {
font-family: "DOTMBold";
src: url("DOTMBold.TTF");
}
#font-face {
font-family: "LLPIXEL3";
src: url("LLPIXEL3.ttf");
}
#font-face {
font-family: "Technology";
src: url("Technology.ttf");
}
#font-face {
font-family: "The Led Display St";
src: url("The Led Display St.ttf");
}
#clock1 {
font-family: "Calculator";
font-size: 70px;
}
#clock2 {
font-family: "DOTMBold";
font-size: 70px;
}
#clock3 {
font-family: "LLPIXEL3";
font-size: 70px;
}
#clock4 {
font-family: "Technology";
font-size: 70px;
}
#clock5 {
font-family: "The Led Display St";
font-size: 70px;
}
<title>hw18</title>
<div id="clock1"></div>
<div id="clock2"></div>
<div id="clock3"></div>
<div id="clock4"></div>
<div id="clock5"></div>
You just need to move your date creation inside the interval. With your current solution, it will take the current date on startup and put it into the html every 1 second. But still the same date.
Here is a possible solution solution:
setInterval(function() {
// Just move your date creation inside the interval function
var today = new Date();
var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date + " " + time; // Add the time to the date string
// Now it will take the current date and put it in all html elements
document.getElementById('clock1').innerHTML = dateTime;
document.getElementById('clock2').innerHTML = dateTime;
document.getElementById('clock3').innerHTML = dateTime;
document.getElementById('clock4').innerHTML = dateTime;
document.getElementById('clock5').innerHTML = dateTime;
}, 1000);
The issue is that your variable var time is overwriting the function time() so then the setInterval is using the wrong value for the first parameter.
Rename the function
function updateTime() {
var d = new Date();
var s = d.getSeconds();
var m = d.getMinutes();
var h = d.getHours();
span.textContent = h + ":" + m + ":" + s;
}
setInterval(updateTime, 1000);
Related
I am making a music player (just to play one song so i can learn more html) and i want it to display the time at the bottom and it seems the only way to do it is with Javascript. I got it to print the time, but it doesnt display any of the html code, only the time shows.
function update() {
var today = new Date();
var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date + ' ' + time;
document.body.innerHTML = dateTime
}
window.onload = function() {
update();
setInterval(update,
body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
height: 100vh;
}
h1,
h2 {
background: -webkit-linear-gradient(purple, pink);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 30px;
text-align: center;
align-content: center;
}
<h2>Hall Of Fame</h2>
<img src=https://dl.dropbox.com/s/uw9v5ro9a6650bd/88DFC197-4C1C-45C4-B8A9-85344796CC74.jpeg? height=150px width=1 50px></img>
<body>
<h1>Let's listen to some music</h1>
<div class="audio">
<audio controls>
<source src="https://dl.dropboxusercontent.com/s/trelm7752nmamcm/Ireland%20Boys%20x%20NCK%20-%20Hall%20of%20Fame%20%28Official%20Music%20Video%29.mp3"
type="audio/mpeg"></source>
<source src="https://drive.google.com/file/d/0ByyrPyKgcWhBZ3ViZ19QYllxYjA/view?usp=drivesdk"
type="audio/mpeg"></source>
</audio>
</div>
<marquee scrollamount=2 direction=right>Ireland boys X NCK - Hall Of Fame</marquee>
you are adding time to entire body, you should try this
<script>
function update() {
var timeWrap = document.createElement("div");
timeWrap.setAttribute("id","timeWrap");
var timeWrapEle = document.getElementById("timeWrap");
if(timeWrapEle === null){
document.body.appendChild(timeWrap);
var timeWrapEle = document.getElementById("timeWrap");
}
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
timeWrapEle.innerHTML = dateTime
}
window.onload = function() {update(); setInterval(update, 1000);}
</script>
Add a container to your HTML for the time display...
<div id="timedisplay"></div>
then replace your document.body.innerHTML = dateTime with
let timeContainer = getElementById("timedisplay");
timecontainer.innerHTML = datetime;
I keep on getting Uncaught TypeError: Cannot set property 'innerHTML' of null on the time where it tells u the day, hour, minute. "timeDiv2.innerHTML = 'it\'s ' + today + ' ' + hour + ':' + minutes + suffix + '';" this the one always being error or when it closing time.it changes to the error or stays at the same line. am i writing it correct?
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'http://www.weebly.com/editor/uploads/1/1/3/4/11341626/custom_themes/599346900698327146/files/Gifs/OpenLightOff.png';
imgArray[1] = new Image();
imgArray[1].src = 'http://www.weebly.com/editor/uploads/1/1/3/4/11341626/custom_themes/599346900698327146/files/Gifs/OpenLightOn.gif';
var now = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var today = weekday[now.getDay()];
var dayOfWeek = now.getDay();
var hour = now.getHours();
var minutes = now.getMinutes();
var suffix = hour >= 12 ? "PM" : "AM";
var checkTime2 = function() {
var timeDiv2 = document.getElementById('timeDiv2');
//add AM or PM
// add 0 to one digit minutes
if (minutes < 10) {
minutes = "0" + minutes
};
if ((dayOfWeek == 1 || dayOfWeek == 2 || dayOfWeek == 3 || dayOfWeek == 4 || dayOfWeek == 0 ) && hour >= 6 && hour <= 21) {
hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
timeDiv2.innerHTML = 'it\'s ' + today + ' ' + hour + ':' + minutes + suffix + '<br><center><img style="width:100%;top:0px;border-radius:10px;" src= '+imgArray[1].src+'></center>';
timeDiv2.className = 'open';
}
else if ((dayOfWeek == 5 || dayOfWeek == 6) && hour >= 6 && hour <= 22){
hour = ((hour + 11) % 12 + 1);
timeDiv2.innerHTML = 'it\'s ' + today + ' ' + hour + ':' + minutes + suffix + '<br><center><img style="width:100%;top:0px;border-radius:10px;" src= '+imgArray[1].src+'></center>';
timeDiv2.className = 'open';
}
else {
if (hour == 0 || hour > 5) {
hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
}
timeDiv2.innerHTML = 'It\'s ' + today + ' ' + hour + ':' + minutes + suffix + '<br><center><img style="width:100%;top:0px;border-radius:10px;" src= '+imgArray[0].src+' ></center>';
timeDiv2.className = 'closed';
}
};
var currentDay = weekday[now.getDay()];
var currentDayID = "." + currentDay; //gets todays weekday and turns it into id
$(currentDayID).toggleClass("today"); //hightlights today in the view hours modal popup
checkTime2();
[id ^="timeDiv"]
{
width:100%;
background: transparent;
margin: 0 auto;
border-radius: 3px;
/* -webkit-box-shadow: 0 8px 16px -8px #adadad;
-moz-box-shadow: 0 8px 16px -8px #adadad;
box-shadow: 0 8px 16px -8px #adadad;*/
display:block;
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.5); /* Black w/ opacity */
}
.day {
display: inline-block;
float: left;
}
.time {
display: inline-block;
float: right
}
.today {
color: rgb(200, 85, 39);
font-weight: 600;
}
.closed {
color: rgba(231, 76, 60, 0.85);
}
.open {
position:relative;
color: #27ae60;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="timeDiv2"></div>
Since the timeDiv2 element is part of your DOM, the best chance is that you run the javascript code before the HTML is being completely loaded.
You can fix this by calling the checkTime2() function only once the page has completely loaded:
$(function() {
checkTime2();
});
You are attempting you manipulate your DOM before it has loaded, try one of the following.
1.
Load your script as the last part of your body.
2.
Use the DOMContentLoaded event.
document.addEventListener('DOMContentLoaded', function () {
/** Your code here... **/
});
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
3.
If you are using jQuery then,
$(document).ready(function () {
/** Your code here... **/
});
I'm trying to make an updating JavaScript clock on my webpage. The problem I'm having is that, while the value itself updates (I use alert(timeNow) to show the value and make sure it's updating), the clock on the website doesn't. I was just wondering if there was something I was missing, or if I've just happened to come across something that I can't quite do. I'd prefer if there was a way to do it using jQuery, as I understand that a little better than normal JavaScript.
Javascript:
function updateClock() {
var thisDate = new Date();
if (thisDate.getHours() > 11 && thisDate.getHours() != 0) {
var Hours = Math.abs(thisDate.getHours() - 12);
var AmPm = "PM"
} else {
var Hours = thisDate.getHours()
var AmPm = "AM"
}
if (thisDate.getMinutes() < 10) {
var Mins = "0" + thisDate.getMinutes();
} else {
var Mins = thisDate.getMinutes();
};
var timeNow = thisDate.getDate() + "/" + (thisDate.getMonth() + 1) + "/" + thisDate.getFullYear() + " " + Hours + ":" + Mins + " " + AmPm;
return timeNow;
};
setInterval(updateClock, 1000);
$("span#time").append(updateClock());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="time"></span>
You are not consuming the return value of updateClock function, thus the updated time is not reflecting.
You should update the text of time span
Use
setInterval(function(){
$("span#time").text(updateClock());
}, 1000);
You are returning the time in the function updateClock(). What you actually want to do is to set it into the DOM at the end of updateClock(). Here is an updated example:
function updateClock() {
var thisDate = new Date();
if (thisDate.getHours() > 11 && thisDate.getHours() != 0) {
var Hours = Math.abs(thisDate.getHours() - 12);
var AmPm = "PM"
} else {
var Hours = thisDate.getHours()
var AmPm = "AM"
}
if (thisDate.getMinutes() < 10) {
var Mins = "0" + thisDate.getMinutes();
} else {
var Mins = thisDate.getMinutes();
};
var timeNow = thisDate.getDate() + "/" + (thisDate.getMonth()+1) + "/" + thisDate.getFullYear() + " " + Hours + ":" + Mins + " " + AmPm;
$("span#time").text(timeNow);
}
setInterval(updateClock, 1000);
You could of course also just use the returned value of updateClock() to update the DOM. In this way, you would separate the DOM manipulation and the JavaScript time calculation. #Satpal described this way.
Try This...
$(document).ready(function()
{
goforit();
});
var dayarray=new Array ("Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday")
var montharray=new Array("January","February","March","April","May","June",
"July","August","September","October","November","December")
function getthedate() {
d = new Date();
d.setUTCFullYear(2004);
d.setUTCMonth(1);
d.setUTCDate(29);
d.setUTCHours(2);
d.setUTCMinutes(45);
d.setUTCSeconds(26);
var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var hours=mydate.getHours()
var minutes=mydate.getMinutes()
var seconds=mydate.getSeconds()
var dn=""
if (hours>=12)
dn=""
if (hours>12){
hours=hours-12
}
if (hours==0)
hours=12
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds
//Hire change font size
var cdate=""
+ mydate.toLocaleString()
+""
if (document.all)
document.all.clock.innerHTML=cdate
else if (document.getElementById)
document.getElementById("clock").innerHTML=cdate
else
document.write(cdate)
}
if (!document.all&&!document.getElementById)
getthedate()
function goforit()
{
if (document.all||document.getElementById)
setInterval("getthedate()",1000)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<SPAN id=clock style="display:block"></SPAN>
setInterval(function() {
$("span#time").text(moment(new Date()).format('DD/M/YYYY LTS'));
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<span id="time"></span>
I'm currently working on a project that will display the amount of time left in a certain time period based on the users current time. Here is the code.
var periods = [
[ '07:45' , '08:34' ],
[ '08:38' , '09:30' ],
[ '09:34' , '10:23' ],
[ '10:27' , '11:16' ],
[ '11:20' , '12:38' ],
[ '12:42' , '15:55' ],
[ '07:00' , ]
];
updateTimePeriods();
setInterval(updateTimePeriods, 1000); // Update every second
function updateTimePeriods() {
var listEl = document.getElementById('periods');
var now = new Date();
var count = periods.length;
listEl.innerHTML='';
for (var i = 0; i < count; i++) {
if(formatTimeRemaining(timeLeft(now, periods[i][1])).charAt(0)!='–') {
child=listEl.appendChild(document.createElement('LI'));
child.innerHTML = periods[i][0] + ' — ' + periods[i][1]
+ ' => Duration: ' + formatUTCTime(duration(periods[i][0], periods[i][1]))
+ ', Remaining: ' + formatTimeRemaining(timeLeft(now, periods[i][1]));
}
}
}
function duration(start, end) {
var startTime = parseTime(start);
var endTime = parseTime(end);
return endTime.getTime() - startTime.getTime();
}
function timeLeft(now, end) {
var nowTime = parseTime(formatTime(now));
var endTime = parseTime(end);
return endTime.getTime() - nowTime.getTime();
}
function parseTime(timeStr) {
var tokens = timeStr.split(':');
return new Date(1970, 0, 1, parseInt(tokens[0], 10), parseInt(tokens[1], 10));
}
function formatUTCTime(time) {
var date = new Date(time);
return padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes());
}
function formatTime(time) {
var date = new Date(time);
return padZero(date.getHours()) + ':' + padZero(date.getMinutes());
}
function formatTimeRemaining(time) {
var sign = '+';
if (time < 0) { time *= -1; sign = '–'; }
var date = new Date(time);
return sign + padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes()) + ':' + padZero(date.getUTCSeconds());
}
function padZero(n) { return ('00' + n).substr(-2); }
body {
background-color: #A00000;
background-size: cover;
margin: 0;
padding: 0;
}
.outer-box {
border: 3px solid black;
height: true;
width: 75%;
padding: 10px;
margin: 10px auto 10px auto;
border-radius: 10px;
background-color: white;
text-align:center;
}
#periods {
border-radius: 5px;
margin: 20px auto 20px auto;
padding: 5px;
font-weight: bold;
text-align: center;
list-style-type: none;
}
<div class="outer-box">
<ul id="periods"></ul>
</div>
My goal is only display to the user the amount of time left in the current time period instead of all of them. And if its in between a time period it shows the amount of time until the next one occurs. The issue is once all the times occur I need to tell him much time until the start of the next time which occurs on a different day. To elaborate, currently if all the time periods occur it displays a blank space because there is nothing to display and all the times are negative. I want to display the amount of time until the next days starting time.
You should break the for loop as you create the new LI element. This way it should only show the actual time period.
for (var i = 0; i < count; i++) {
if(formatTimeRemaining(timeLeft(now, periods[i][1])).charAt(0)!='–') {
child=listEl.appendChild(document.createElement('LI'));
child.innerHTML = periods[i][0] + ' — ' + periods[i][1]
+ ' => Duration: ' + formatUTCTime(duration(periods[i][0], periods[i][1]))
+ ', Remaining: ' + formatTimeRemaining(timeLeft(now, periods[i][1]));
break;
}
}
My goal is to display to the user ONLY the time left in there current period. Currently it displays all of the periods duration and time reaming, I only want to display one, which is the time frame they are currently in.
var periods = [
[ '07:45' , '08:34' ],
[ '08:38' , '09:30' ],
[ '09:34' , '10:23' ],
[ '10:27' , '11:16' ],
[ '11:20' , '12:38' ],
[ '12:42' , '13:31' ],
[ '13:35' , '14:25' ]
];
generatePeriods();
updateTimePeriods();
setTimeout(updateTimePeriods, 1000); // Update every second
function generatePeriods() {
var listEl = document.getElementById('periods');
periods.forEach(function(period) {
listEl.appendChild(document.createElement('LI'));
});
}
function updateTimePeriods() {
var now = new Date();
var children = document.getElementById('periods').childNodes;
var i = 0;
for (var i = 0; i < children.length; i++) {
var child = children[i];
child.innerHTML = periods[i][0] + ' — ' + periods[i][1]
+ ' => Duration: ' + formatUTCTime(duration(periods[i][0], periods[i][1]))
+ ', Remaining: ' + formatTimeRemaining(timeLeft(now, periods[i][1]));
}
}
function duration(start, end) {
var startTime = parseTime(start);
var endTime = parseTime(end);
return endTime.getTime() - startTime.getTime();
}
function timeLeft(now, end) {
var nowTime = parseTime(formatTime(now));
var endTime = parseTime(end);
return endTime.getTime() - nowTime.getTime();
}
function parseTime(timeStr) {
var tokens = timeStr.split(':');
return new Date(1970, 0, 1, parseInt(tokens[0], 10), parseInt(tokens[1], 10));
}
function formatUTCTime(time) {
var date = new Date(time);
return padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes());
}
function formatTime(time) {
var date = new Date(time);
return padZero(date.getHours()) + ':' + padZero(date.getMinutes());
}
function formatTimeRemaining(time) {
var sign = '+';
if (time < 0) { time *= -1; sign = '–'; }
var date = new Date(time);
return sign + padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes()) + ':' + padZero(date.getUTCSeconds());
}
function padZero(n) { return ('00' + n).substr(-2); }
body {
background-color: #A00000;
background-size: cover;
margin: 0;
padding: 0;
}
.outer-box {
border: 3px solid black;
height: true;
width: 75%;
padding: 10px;
margin: 10px auto 10px auto;
border-radius: 10px;
background-color: white;
text-align:center;
}
#periods {
border-radius: 5px;
margin: 20px auto 20px auto;
padding: 5px;
font-weight: bold;
text-align: center;
}
<div class="outer-box">
<div id="periods"></div>
</div>
You can check the time using the following snippet :
for (var i = 0; i < children.length; i++) {
var child = children[i];
var now = new Date();
var nowHour = now.getHours();
if(periods[i][0] > nowHour) {
child.innerHTML = periods[i][0] + ' — ' + periods[i][1]
+ ' => Duration: ' + formatUTCTime(duration(periods[i][0], periods[i][1]))
+ ', Remaining: ' + formatTimeRemaining(timeLeft(now, periods[i][1]));
}
}
First, i have slightly changed your HTML, li should be child of ul.
Then i've removed your generatePeriods() function.
If you don't want to show all periods (just positive) - you don't need empty li elements.
Then i slightly modified your updateTimePeriods() function:
function updateTimePeriods() {
var listEl = document.getElementById('periods');
var now = new Date();
var count = periods.length;
listEl.innerHTML='';
for (var i = 0; i < count; i++) {
if(formatTimeRemaining(timeLeft(now, periods[i][1])).charAt(0)!='–') { // check if negative
child=listEl.appendChild(document.createElement('LI'));
child.innerHTML = periods[i][0] + ' — ' + periods[i][1]
+ ' => Duration: ' + formatUTCTime(duration(periods[i][0], periods[i][1]))
+ ', Remaining: ' + formatTimeRemaining(timeLeft(now, periods[i][1]));
}
}
}
So, now it should work like this:
var periods = [
[ '07:45' , '08:34' ],
[ '08:38' , '09:30' ],
[ '09:34' , '10:23' ],
[ '10:27' , '11:16' ],
[ '11:20' , '12:38' ],
[ '12:42' , '15:55' ],
[ '13:35' , '15:56' ]
];
updateTimePeriods();
setInterval(updateTimePeriods, 1000); // Update every second
function updateTimePeriods() {
var listEl = document.getElementById('periods');
var now = new Date();
var count = periods.length;
listEl.innerHTML='';
for (var i = 0; i < count; i++) {
if(formatTimeRemaining(timeLeft(now, periods[i][1])).charAt(0)!='–') {
child=listEl.appendChild(document.createElement('LI'));
child.innerHTML = periods[i][0] + ' — ' + periods[i][1]
+ ' => Duration: ' + formatUTCTime(duration(periods[i][0], periods[i][1]))
+ ', Remaining: ' + formatTimeRemaining(timeLeft(now, periods[i][1]));
}
}
}
function duration(start, end) {
var startTime = parseTime(start);
var endTime = parseTime(end);
return endTime.getTime() - startTime.getTime();
}
function timeLeft(now, end) {
var nowTime = parseTime(formatTime(now));
var endTime = parseTime(end);
return endTime.getTime() - nowTime.getTime();
}
function parseTime(timeStr) {
var tokens = timeStr.split(':');
return new Date(1970, 0, 1, parseInt(tokens[0], 10), parseInt(tokens[1], 10));
}
function formatUTCTime(time) {
var date = new Date(time);
return padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes());
}
function formatTime(time) {
var date = new Date(time);
return padZero(date.getHours()) + ':' + padZero(date.getMinutes());
}
function formatTimeRemaining(time) {
var sign = '+';
if (time < 0) { time *= -1; sign = '–'; }
var date = new Date(time);
return sign + padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes()) + ':' + padZero(date.getUTCSeconds());
}
function padZero(n) { return ('00' + n).substr(-2); }
body {
background-color: #A00000;
background-size: cover;
margin: 0;
padding: 0;
}
.outer-box {
border: 3px solid black;
height: true;
width: 75%;
padding: 10px;
margin: 10px auto 10px auto;
border-radius: 10px;
background-color: white;
text-align:center;
}
#periods {
border-radius: 5px;
margin: 20px auto 20px auto;
padding: 5px;
font-weight: bold;
text-align: center;
}
<div class="outer-box">
<ul id="periods"></ul>
</div>
P.S. I've updated periods array because of testing.