PDA

View Full Version : JavaScript Time Help


SDP2006
06-23-2003, 08:03 PM
There is nothing wrong with this code other than the time when there is a "0" in front of it (i.e. 3:02) it will display "3:2". Any ideas guys?


<script type="text/javascript">
// THIS SCRIPT WRITTEN BY STEVIE PEELE
// WILL DISPLAY TIME AS "6:45"
var d = new Date()
var hour=new Array("12","1","2","3","4","5","6","7","8","9","10","11","12","1","2","3","4","5","6","7","8","9","10","11","12")
document.write(hour[d.getHours()])
document.write(":")
document.write(d.getMinutes())
</script>


Thanks :thumbsup:

kansel
06-23-2003, 09:29 PM
change document.write(d.getMinutes()) to

document.write(d.getMinutes()<10?"0"+d.getMinutes():d.getMinutes());

this is shorthand for
if(d.getMinutes < 10) document.write("0");
document.write(d.getMinutes());

cheesebagpipe
06-23-2003, 09:33 PM
document.write(hour[d.getHours()])
document.write(":");
var m = d.getMinutes();
document.write((m>9)?m:'0'+m);
</script>

Why call d.getMinutes() twice?

kansel
06-23-2003, 09:34 PM
Then again you could functionalize this to use it over and over again:

function hhmm(){
var hours = new Date().getHours();
var minutes = new Date().getMinutes();
return (hours%12==0?"12":hours%12) + ":" + (minutes<10?"0"+minutes:minutes) + (hours<12?" AM":" PM");
}


usage: document.write(hhmm());
or var time_string = hhmm();

if you don't like the AM/PM display, remove the last plus sign and parenthesis block that follows it:

return (hours%12==0?"12":hours%12) + ":" + (minutes<10?"0"+minutes:minutes);

kansel
06-23-2003, 09:38 PM
cheese- for that matter, why have a 24 element array whose only purpose is to do this job?
(hours%12==0?"12":hours%12)

i'd like to see a 60 element array just for the minutes:
var minute = new Array("00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59");

cheesebagpipe
06-23-2003, 11:02 PM
cheese- for that matter, why have a 24 element array whose only purpose is to do this job?Didn't say that; was just making a point about putting a retrieved value into a variable.