Reputation: 1939
Heres the final result. I'm updating it so that in the future, questions like the one I originally posted (how to make a 12 hour clock) can be forwarded to this thread for reference. Thanks to MrChief for his help!
<html>
<head>
<script type="text/javascript">
String.prototype.lpad = function(padString, length) {
var str = this;
while (str.length < length) {
str = padString + str;
}
return str;
}
function timeNow() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var tt = (h >= 12) ? " pm" : " am";
time = (h - 12).toString().lpad("0", 2) + ":" + m.toString().lpad("0", 2) + ":" + s.toString().lpad("0", 2) + tt;
document.getElementById('txt').innerHTML=time;
var timer = setTimeout(timeNow,500);
}
</script></head>
<body onload="timeNow()">
<div id="txt"></div>
</body></html>
Upvotes: -1
Views: 926
Reputation: 76258
Maybe you meant
i="0" + i + "am";
^
and your checkTime
function is missing closing parens.
Update:
There are better ways to do padding. Here's a function that modifies the string
's prototype which adds a left padding function to string objects.
//pad left
String.prototype.lpad = function(padString, length) {
var str = this;
while (str.length < length)
str = padString + str;
return str;
}
Using that, your function becomes much simpler:
function timeNow() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var tt = (h >= 12) ? " pm" : " am";
time = h.toString().lpad("0", 2) + ":" + m + ":" + s.toString().lpad("0", 2) + tt;
alert(time);
}
Demo: http://jsfiddle.net/mrchief/kTQnM/7/
Here's full demo using your HTML: http://jsfiddle.net/mrchief/kTQnM/10/
Upvotes: 4
Reputation: 4812
Change
else (10<i<12)
to else (10 < i && i<12)
(1010, this becomes (true)<12 which will evaluate to true.
Upvotes: 0
Reputation: 65
You are trying to set am/pm from minutes and seconds rather than from hours. It should be a separate function for example
var am_pm = (h < 12) ? 'am' : 'pm';
m = (m < 10) ? '0' + m : m;
s = (s < 10) ? '0' + s : s;
Also, several syntax errors e.g.
else (10<i<12)
should be else if (i > 10 && i < 12)
Upvotes: 0
Reputation: 100667
function checkTime
is missing its closing parenthesis.am
and pm
to both your minutes and seconds. Try running your JavaScript in an environment like jsFiddle during development.
Here's your code: http://jsfiddle.net/kTQnM/2/
To get AM/PM working as you need, suggest using this method: Converting 24 hour time to 12 hour time w/ AM & PM using Javascript
Upvotes: 2