Skip to content

Instantly share code, notes, and snippets.

@apguan
Last active June 18, 2016 22:52
Show Gist options
  • Save apguan/019011d903dba0189b08b1e27c2e4bda to your computer and use it in GitHub Desktop.
Save apguan/019011d903dba0189b08b1e27c2e4bda to your computer and use it in GitHub Desktop.
JS Clock
<body id="body">
<div class="container-fluid" id="time">
<div id="date">
</div>
<p id="mem">The time is...</p>
<div id="clock">
</div>
</div>
</body>

JS Clock

A small demonstration of responsive JS app with built in time functions. Dates are displayed with the proper suffixes, while the 24 hour clock has been converted to a 12 hour clock.

A Pen by Allen Guan on CodePen.

License.

var formatTime = function(i) {
if (i < 10) {
var format = "0" + i;
return format;
} else {
return i
}
};
var formatHour = function(i) {
if (i > 12) {
var formHour = i - 12;
return formHour;
} else {
return i;
}
};
var amPM = function(i){
if (i > 12) {
return "PM";
} else {
return "AM"
}
}
var dateFormat = function(i){
switch (i) {
case (1):
case (21):
case (31):
return i + "st";
break;
case (2):
case (22):
return i + "nd";
case (3):
case (23):
return i + "rd";
break;
default:
return i + "th";
breakk;
}
};
// variables must be inside this updateTime function because all of the functions inside are refreshed by setInterval.
var updateTime = function(){
var today = new Date();
//date
var date = today.getDate();
//time
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
//format the minutes and the seconds to be double digits
var displayClock = formatHour(h) + ':' + formatTime(m) + ':' + formatTime(s) + amPM(h);
var displayDate = 'Today is the ' + dateFormat(date);
$(document).ready(function(){
$('#date').html(displayDate);
$('#clock').html(displayClock).css({'color':'red'});
});
};
//use setInterval for repetition. setTimeout only happens once as advised by JS documentation.
setInterval(updateTime,1000)
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
body {
background-color: black;
font-family: 'Anton', sans-serif;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
a {
color: gray;
}
#date {
color: white;
font-size: 50px;
}
#clock {
color: white;
font-size: 100px;
}
p#mem {
color: white;
font-size: 35px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment