Web Analytics Made Easy -
StatCounter Javascript date time problem - CodingForum

Announcement

Collapse
No announcement yet.

Javascript date time problem

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Javascript date time problem

    Hi

    I'm using a small javascript to display a clock on my site, and i want the clock to display 24H-format. I also want it to add a zero in front of the hour or minutes if the hour or minute is <10.

    This is my code, and the adding of a zero in front of Hour or Minute doesnt work so if the clock is actually 07:08 it shows 7:8.
    Code:
    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);
    	h=timeFormat(h);
    		
    		document.getElementById('date').innerHTML=h+":"+m;
    		t=setTimeout('startTime()',500);
    		}
    
    	function checkTime(i)
    	{
    		if (i<10)
    		{
    			i=0 + i;
    			}
    		return i;
    		}
    		
    	function timeFormat(j)
    	{
    		if (j>24)
    		{
    			j= j - 12;
    			}
    		return j;
    		}
    What is wrong in the code?

  • #2
    You're using a number, not a string... so it's doing a numeric addition not a string one.

    i = '0' + i;

    Though honestly, just return the value instead. Ternary operators would really simplify your code here.

    Code:
    function checkTime(i) {
    	return ((i < 10) ? '0' : '') + i;
    }
    
    function timeFormat(j) {
    	return j > 24 ? j - 12 : j;
    }
    Those quotes around the zero? Yeah, they're that important. If you don't make it a string, you get math... and i + numeric zero is still i.

    Don't worry, easy mistake -- we all make it at the start with JavaScript thanks to the lack of strict typecasting or explicit operators... which is why no matter what people do with it, it's still a toy language.
    Walk the dark path, sleep with angels, call the past for help.
    https://cutcodedown.com
    https://medium.com/@deathshadow

    Comment


    • #3
      Thank you very much deathshadow. This was great help :-)

      Comment

      Working...
      X