Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Showing the time

Status
Not open for further replies.

Jonnn

Programmer
Nov 17, 2004
135
0
0
GB
I have the following script to show the time on my webpage

Code:
function show_time() {
var todays_date = new Date(); // gets current time and date

var get_month = todays_date.getMonth();
var month_string = month[get_month];  	// Month in a string

var get_dom = todays_date.getDate();
var dom_string = day_of_month[get_dom]; // Day of month in a string

var get_day = todays_date.getDay();
var day_string = day[get_day]; 		// Day of week in a string

var hours = todays_date.getHours();
var minutes = todays_date.getMinutes();
var seconds = todays_date.getSeconds();

[COLOR=red]
if(hours < 10) {
hours = "0" + todays_date.getHours();
}

if(minutes < 10) {
minutes = "0" + todays_date.getMinutes();
}

if(seconds < 10) {
seconds = "0" + todays_date.getSeconds();
}
[/color]
document.getElementById('show_date').innerHTML = dom_string + " " + month_string + " / " + hours + ":" + minutes + " " + seconds;

setTimeout("show_time()",1000);
}

The highlighted code in red is what I had to use to debug the time.

For every hour, minute, and second. If the number was below 10 it would show as 1,2,3,4 etc, instead of 01,02,03

Is this a bug in the time or where they not thinking when they made it...

---------------------------------------
Thanks for your help,
Jon

 
Is this a bug in the time or where they not thinking when they made it...

Neither. The values are delivered to you as numbers. Computers do not deliver numbers with prefixed 0s... that is pure formatting and should be done by the programmer as desired.

Dan



[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
You can force it to treat + as a concatenator by appending some empty strings to the code...
Code:
if(hours < 10) {
hours = [COLOR=red][b]"" + [/b][/color]"0" + todays_date.getHours();
}

if(minutes < 10) {
minutes = [COLOR=red][b]"" + [/b][/color]"0" + todays_date.getMinutes();
}

if(seconds < 10) {
seconds = [COLOR=red][b]"" + [/b][/color]"0" + todays_date.getSeconds();
}
I know it's only debug code... but it's a nice trick to be aware of.

Cheers,
Jeff

[tt]Jeff's Page [/tt][tt]@[/tt][tt] Code Couch
[/tt]
 
What do you guys mean. Im so confused :)

Do you mean to make the variable a string?

How else could I have done it?

That was just off the top of my head...

You guys would have pissed yourself laughing if you had seen what I had programmed in before that. It was like nearly a page long. Then I thought about it ... I was like ... oh my ...

Please explain what you mean as I am still learning...

---------------------------------------
Thanks for your help,
Jon

 
Jon,

Jeff was confusing the problem you had with a different, but common problem where people need to typecast variables as strings.

The code you've got is absolutely fine.

Dan



[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
just a few suggestions:

1. INDENT YOUR CODE!!! (Every programmer learns this in CS 101 for a reason)
2. change this:
Code:
if(hours > 12) {
switch(hours) {
case 13: hours = 1;
break;
case 14: hours = 2;
break;
case 15: hours = 3;
break;
case 16: hours = 4;
break;
case 17: hours = 5;
break;
case 18: hours = 6;
break;
case 19: hours = 7;
break;
case 20: hours = 8;
break;
case 21: hours = 9;
break;
case 22: hours = 10;
break;
case 23: hours = 11;
break;
default: alert("Problem with time");
}
}
to this:
Code:
hours = (hours > 12) ? hours - 12 : hours;

3. change the completed_function_once variable to a boolean. When a variable has an on/off status it's always much cleaner to use a boolean variable instead of a string.

-kaht

...looks like you don't have a job, so why don't you get out there and feed Tina.
headbang.gif
[rockband]
headbang.gif
 
why indent my code?

I understand that you have to in other languages but why JavaScript.

Thanks for the advice on the rest, I never really got the chance to simplify it. Just made it and it worked well :)

Apart from that? what do you think?


---------------------------------------
Thanks for your help,
Jon

 
why indent my code?
I understand that you have to in other languages but why JavaScript.

You'd do it in javascript for the same reason that you would do it in any other languages. It makes for MUCH easier code maintenance later on in the event that anybody ever goes back to make a modification to existing code. Take something like this for example:
Code:
while (true) {
if (a == b || b == c) {
a = b;
if (b != c) {
a = c;
b = c;
while (d < e) {
j = true;
d++;
}
if (j) {
a--;
b++;
}
switch(a) {
case 1:
if (b == c) {
alert("wow");
while (!a) {
a--;
}
}
break;
case 2:
return true;
break;
}
for (i = 1; i < 10; i++) {
if (i == 5) {
if (a == 1) {
alert("i equals 5 and a equals 1");
}
}
}
}
}
(disclaimer: this code does nothing)
The code I provided above is perfect JavaScript syntax. So, it s feasible that you may see something like this in a JavaScript program. However, if you tried to run this you're going to get an error: "} expected". Can you tell me where it's supposed to go? If the code was indented I could tell you immediately, however it's gonna be a nightmare to parse that out to see where it's supposed to be. Indenting helps you think of your code in sections. For an "if block", it's easy to see what's indented and know that everything belongs to that "if condition". If I were you I would get used to indenting in any program language that you code in because it makes the code cleaner, easier to maintain, and helps prevent silly errors like the one I just posted.

Other than the things I listed, I think your code looks fine. I would probably use the ternary operator a bit more as well.... but that's merely a matter of preference, because I usually try to condense my code to as few lines as possible.

(on a side note, the "}" that I took out above came right before the switch statement, but logically you could have put in the "}" in many different places, which makes it even harder to debug without proper indentation.)

-kaht

...looks like you don't have a job, so why don't you get out there and feed Tina.
headbang.gif
[rockband]
headbang.gif
 
Do you mean like this?

Code:
function show_time() 
{
	var todays_date = new Date(); // gets current time and date

	var get_month = todays_date.getMonth();
	var month_string = month[get_month];  	// Month in a string

	var get_dom = todays_date.getDate();
	var dom_string = day_of_month[get_dom]; // Day of month in a string

	var get_day = todays_date.getDay();
	var day_string = day[get_day]; 		// Day of week in a string

	var hours = todays_date.getHours();
	var minutes = todays_date.getMinutes();
	var seconds = todays_date.getSeconds();

	var am_or_pm = "am";

	if(minutes < 10) 
{
	minutes = "0" + todays_date.getMinutes();
}

	if(seconds < 10) 
{
	seconds = "0" + todays_date.getSeconds();
}

	if(hours < 12) 
{
	am_or_pm = "am";
}

	else 
{
	am_or_pm = "pm";
}

	if(hours > 12) 
{
	switch(hours) 
{
	case 13: hours = 1;
	break;
	case 14: hours = 2;
	break;
	case 15: hours = 3;
	break;
	case 16: hours = 4;
	break;
	case 17: hours = 5;
	break;
	case 18: hours = 6;
	break;
	case 19: hours = 7;
	break;
	case 20: hours = 8;
	break;
	case 21: hours = 9;
	break;
	case 22: hours = 10;
	break;
	case 23: hours = 11;
	break;
	default: alert("Problem with time");
}
}

	if(completed_function_once == "yes") 
{
	if(seconds == 0) 
{
	document.getElementById('show_date').innerHTML = dom_string + " " + month_string + " / " + hours + ":" + minutes + am_or_pm;
	setInterval("show_time()", 60000);
}
}

	else 
{
	document.getElementById('show_date').innerHTML = dom_string + " " + month_string + " / " + hours + ":" + minutes + am_or_pm
}

	completed_function_once = "yes";

	setTimeout("show_time()", 1000);
}

---------------------------------------
Thanks for your help,
Jon

 
No, like this. As you can see on any one particular block of code (if block, switch block, etc.), everything that meets that condition is indented 3 spaces (some ppl use 4, I prefer 3) so that it is easy to see what code will fall under that condition. And then when that block of code is completed the closing bracket "}" is unindented so that it starts at the same position as the command that started it (if, switch, etc.)
Code:
function show_time() {
   var todays_date = new Date(); // gets current time and date

   var get_month = todays_date.getMonth();
   var month_string = month[get_month];      // Month in a string

   var get_dom = todays_date.getDate();
   var dom_string = day_of_month[get_dom]; // Day of month in a string

   var get_day = todays_date.getDay();
   var day_string = day[get_day];         // Day of week in a string

   var hours = todays_date.getHours();
   var minutes = todays_date.getMinutes();
   var seconds = todays_date.getSeconds();

   var am_or_pm = "am";

   if(minutes < 10) {
      minutes = "0" + todays_date.getMinutes();
   }

   if(seconds < 10) {
      seconds = "0" + todays_date.getSeconds();
   }

   if(hours < 12) {
      am_or_pm = "am";
   }
   else {
      am_or_pm = "pm";
   }

   if(hours > 12) {
      switch(hours) {
         case 13:
            hours = 1;
            break;
         case 14: 
            hours = 2;
            break;
         case 15: 
            hours = 3;
            break;
         case 16: 
            hours = 4;
            break;
         case 17: 
            hours = 5;
            break;
         case 18: 
            hours = 6;
            break;
         case 19: 
            hours = 7;
            break;
         case 20: 
            hours = 8;
            break;
         case 21: 
            hours = 9;
            break;
         case 22: 
            hours = 10;
            break;
         case 23: 
            hours = 11;
            break;
         default:
            alert("Problem with time");
      }
   }

   if(completed_function_once == "yes") {
      if(seconds == 0) {
         document.getElementById('show_date').innerHTML = dom_string + " " + month_string + " / " + hours + ":" + minutes + am_or_pm;
         setInterval("show_time()", 60000);
      }
   }
   else {
      document.getElementById('show_date').innerHTML = dom_string + " " + month_string + " / " + hours + ":" + minutes + am_or_pm
   }
   completed_function_once = "yes";
   setTimeout("show_time()", 1000);
}
Taking this block for a specific example:
[tt] if(minutes < 10) {
minutes = "0" + todays_date.getMinutes();
}[/tt]
as you can see the if statement starts at position 4, indented in 3 spaces because it belongs to the function (where the initial indentation begins). If minutes < 10, then the code within the if block executes. The code to be executed is indented 3 spaces so it is easy to look at a glance what belongs to this block of code. Finally, when the block is completed the closing bracket "}" is set back at position 4 to signify that the block of code is completed. Now... With something this simple it's not that necessary to have to indent the if block to be able to easily read it, but when you start getting into nested blocks of code (like the one I provided above) it becomes very easy to lose track of where your logical process was going, and deciphering where blocks of code begin and end can become a nightmare. That's why it's good practice to indent all your code (even easy 1 line blocks like the one I just demonstrated) just so that your code is clean and easily manageable.

And I also rewrote your code with way less lines, it might help you see how you could potentially improve your coding techniques.
Code:
function show_time() {
   var todays_date = new Date(); // gets current time and date

   var get_month = todays_date.getMonth();
   var month_string = month[get_month];      // Month in a string

   var get_dom = todays_date.getDate();
   var dom_string = day_of_month[get_dom]; // Day of month in a string

   var get_day = todays_date.getDay();
   var day_string = day[get_day];         // Day of week in a string

   var hours = todays_date.getHours();
   var minutes = todays_date.getMinutes();
   var seconds = todays_date.getSeconds();

   [b][COLOR=red]var am_or_pm = (hours < 12) ? "am" : "pm";

   minutes = (minutes < 10) ? "0" + minutes : minutes;
   hours = (hours > 12) ? hours - 12 : hours;[/color][/b]

   document.getElementById('show_date').innerHTML = dom_string + " " + month_string + " / " + hours + ":" + minutes + am_or_pm;
   setTimeout("show_time()", [b][COLOR=red](60 - seconds) * 1000 + 1[/color][/b]);
   [i][COLOR=grey]// the [b]+ 1[/b] prevents a 0 in the timeout function[/color][/i]
}
One quick question, you are making reference to arrays named month, day_of_month, and day in your FAQ, but they are not defined anywhere. Is this something that got left out?

-kaht

...looks like you don't have a job, so why don't you get out there and feed Tina.
headbang.gif
[rockband]
headbang.gif
 
All very valuable techniques and styles, Kaht. I personally prefer TABs over SPACEs, more personal preference really.

I take indenting code for granted... well I did until I recently did a contract where the previous programmer not only removed all indenting but also moved all functions into a single line. It took quite some time (that was effectively wasted) to get the code back into a state where it was able to be properly debugged.

It's good to see some more FAQs being written, and it's a great way to have peer code-review (if you are into that kind of thing).

Keep on it, Jon... these techniques and styles become second nature very quickly, and you will become a better coder faster if you follow (the concept of) them.

Cheers,
Jeff

[tt]Jeff's Page [/tt][tt]@[/tt][tt] Code Couch
[/tt]
 
Jonnn,

Forget about YOU for a second... another reason to indent your code, the way kaht describes, is for when you are asking for help from US! People who post well-formatted code inside of the [ignore]
Code:
[/ignore] tags are more likely to get help than those who don't. I haven't run actual statistics on this, but if I were a betting man...

--Dave
 
Thanks guys!

Kaht - I guess I need to start using them type of statements more regularly. They do the same job, with less lines. Thanks for your comments and advice on indenting my code. I will definitely put this to use. And, I have made an error on my FAQ, I have forgotten to put in my arrays... oops :-( ... I will edit this ASAP

Jeffy - Thanks for your comments, I think writing FAQ's is very helpful. I will always write one when I have alot of knowledge on a certain subject.

Dave - I understand that indenting your code can help all you guys, but PLEASE understand that there are alot of beginners out there that know nothing about indenting code, and to say people who indent their code are more likely to get help is just outrageous. I think people should show more respect to learners if that is the case.

On other news.

I am starting a Foundation Degree in Computing :)

I start next week, the course has alot in store for me in the world of programming. hehehehe :)

---------------------------------------
Thanks for your help,
Jon

 
Yeah, Jonnn... I understand.

Understand too that for many of us, helping out on this board is a diversion that keeps us from the work we're paid for (although we can claim continuing education for it!) or from something else we otherwise "should" be doing.

I think it's just reality that if a question is too verbose or the provided code isn't easy to make out within a couple of minutes, there are those among us, who might otherwise be helpful, who will decide to pass on the question. For small code fragments like the ones you posted, it's probably no big deal. I may be only speaking for myself, but I've opened questions before, taken one look, and said "no thanks... kaht'll get this one!" :)

I don't think it's so outrageous at all to suggest that the more helpful the user who posts the question is in providing the needed details up front in a user-friendly fashion, the more likely that person is to get help.

As for being a beginner: we've all been there. I didn't use to use the [ignore]
Code:
[/ignore] tags, but I got some feedback about that and now I use them. I certainly didn't mean my post to sound like a threat in any way ("do what we say or that's the last help you'll get"), merely a tip to help you get "the best answers by posting the best questions" (to paraphrase someone's signature who posts regularly on Tek-Tips). I can see that my "Forget about YOU for a second" probably sounded off-putting... I assure you, I was merely trying to obtain a balanced sentence-structure (YOU/US). I didn't mean to imply that there is anything wrong with YOU per-se. 'just wanted to add another reason to the pile in favor of indenting code.

Meanwhile, good luck with your coarsework! Going back to school is a really enormous undertaking!

--Dave
 
I am starting a Foundation Degree in Computing

Congratulations, best of luck to you.

-kaht

...looks like you don't have a job, so why don't you get out there and feed Tina.
headbang.gif
[rockband]
headbang.gif
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top