• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 563
  • Last Modified:

Javascript: render time in AM:PM format

With the w#schools code below:

1)How do I change this to get the time in as 1:32 PM?
2) Is there a more compact way to return the time? This seems to me like more code than onw would need.

Thanks,
John

<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m;
t=setTimeout('startTime()',500);
}
 
function checkTime(i)
{
if (i<10)
  {
  i="0" + i;
  }
return i;
}
</script>

Open in new window

0
gabrielPennyback
Asked:
gabrielPennyback
  • 3
1 Solution
 
DanielWillmottCommented:

<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
var ampm="AM";
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
if(h>12) {
h=h-12;
ampm="PM";
}
document.getElementById('txt').innerHTML=h+":"+m+" "+ampm;
t=setTimeout('startTime()',500);
}
 
function checkTime(i)
{
if (i<10)
  {
  i="0" + i;
  }
return i;
}
</script>

Open in new window

0
 
gabrielPennybackAuthor Commented:
Well virtually nothing is going right today, so there might now be anything wrong with the code (it worked for me before  with, but it returns nothing for me. How about you? Could you test it and let me know?

Thanks,
John


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>
 
<body>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
var ampm="AM";
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
if(h>12) {
h=h-12;
ampm="PM";
}
document.getElementById('txt').innerHTML=h+":"+m+" "+ampm;
t=setTimeout('startTime()',500);
}
 
function checkTime(i)
{
if (i<10)
  {
  i="0" + i;
  }
return i;
}
</script>
 
What's going on?
</body>
</html>

Open in new window

0
 
gabrielPennybackAuthor Commented:
Never mind, I was missing half the code ...  the part that makes it work! Thanks for your answer.

- John
0
 
gabrielPennybackAuthor Commented:
Thanks, Daniel.
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now