|
||||
|
||||
|
6 ~ Dates, Time IF and ELSE(1) (2) (3) (4) (5) (6) (7) (8)Javascript comes pretty well equipped with the tools you need to get and display Times and dates. You have probably seen displays like the following on a web page: There are two ways to create the above message: code it in HTML every time you update your site, or do it the easy way and let "javascript" figure out when your page was modified and write the date and time for you automatically. Here's the code:
<script language="JavaScript">
The 'lastModified' method is a built-in "javascript" function that will extract the time and date from your system and apply this method to the document object. The important things to remember here are the period, which separates all objects and methods, and the case of the method; the 'M' must be capitalized, and all the rest of the word is lower case. All you have to do is insert this code into your document where you want it to show up, and the next time you modify and save your page to disk or upload the document to your server, the function will automatically put that date and time on your page when it's viewed. Javascript can do much more than this, however. For instance, do you remember exactly what time it was when you opened this lesson? In case you can't, I'll tell you: it was according to your computer's clock. Check it out if you want, just hit the refresh button. Here's the code that does it:
<script language="JavaScript"> Okay, let's take it step by step. First, 'pageLoaded' is the variable name I chose, and it takes the value of new Date. The term Date by itself is static; it won't work without the term 'new' thrown in there. So what we are doing is assigning the variable 'pageLoaded' to the object 'new Date'. (The actual object is just 'Date'). In other words, 'pageLoaded' will contain whatever data the methods of 'new Date' come up with. The next line is all one line with no line breaks, even though it may look broken because of your particular browser's screen size; don't throw any carriage returns in there. This line contains three methods of the object 'Date' and it's pretty apparent what these methods do by their names. Notice the format of the 'get' method: lower case except for the first letter of whatever you want to get, which has to be capitalized. I put in the word 'exactly' and the quoted colons not just to make the output more readable, but because without the extra text, "javascript" would think we were dealing with numbers only, and would simply get the hour, minutes and seconds and add them together. The sum of these would be printed to the page. For instance, if the method 'getHours' returned a 5, and 'getMinutes' returned 30, and 'getSeconds' returned 10, they would be added up and the sum 45 would be printed. The plus sign can be used to couple two strings of text, strings to numbers and so on, but without a little careful thought about the outcome some strange things can happen... but let's get back to our dissection. The document.write method will first write 'exactly ' and then we come to our object 'pageLoaded'; this part may be a little hard to understand, but I'll give it my best shot. We know that 'pageLoaded' is an object because we declared right from the start of the script that 'pageLoaded' and 'new Date' were equal to each other, therefore one and the same, and 'new Date' is an object. But 'pageLoaded' is also a variable in a sense, because it will contain several different values in the script. Clear enough? Okay, then. So 'pageLoaded' uses the method 'getHours()' to give us the hour unit of time, then it is reused with the method 'getMinutes()' for the minute value, and finally 'getSeconds()' for the seconds. Then document.write prints these values along with our added bits of formatted text to the page. Here are a few more functions that could be added to the above script:
getYear() . . .returns a two digit value for the year. Did you notice anything odd about what the getMonth function returns? Javascript counts from zero with the getMonth() and getDay() functions, instead of one; to get the right month printed out, you have to add a 'one' to the right result. All these functions return a numeric value. So how would you use 'getDay' to print out 'Sunday" instead of the number '0' ? That's where the IF and ELSE functions come in handy, and we'll get to these shortly. But first, take a look at the following code.
<script language="JavaScript"> Remember, from the chart above we know that this will give us the day of the week. This is the output of this script: That's not very helpful, is it? The code just found that this is day number of the week; to make it tell us more, we have to do a little more programming, and that's where IF can help us out. Introducing IF and ELSE
<script language="JavaScript"> This is what the above will print out:
That's more like it, right? This should show you the power in the simple if statement. If and else are used for branching to different sections of code, depending on whether the arguments, or conditions, are true or false. This is what is termed 'Boolean' in programming jargon, which means something is either true or false, yes or no, a '1' or a '0'. Let's get to the explanation. First, I made a variable and decided to call it "Today" and of course it is declared right from the get-go. All variables need a value, but this one doesn't have one yet, so I gave it a string value; the empty set of quotes does that, even though there is no text defined as yet, there is still the implied value of textual content. So we have a new variable declared. The next line we have discussed already; after that, we come to our if statement. Here's the first if statement again, so you don't have to scroll back up.
if (pageLoaded.getDay()==1) {
Whenever you use 'if', this is the general format. What the code says is: By the way, if it will be easier for you, you could also write out the above code like this: if (pageLoaded.getDay()==1) {Today="Monday"} Either way will work, just do what feels most comfortable for you. Now that we understand a little about the if statement, let's look into how to use its helper, the else statement. ELSE For this example, we'll shorten the code for clarity and we will have to make an intentional wrong entry to be sure that the if statement returns false, so the else statement will be used. We can do it like so:
<script language="JavaScript"> This is the result: Here's what's happenening. As stated earlier, we insured that the if statement would return false by asking if 'pageLoaded.getDay()' was equal to 8 (Remember, getDay() returns only values of 0 to 6). When this statement is read and it is not true, then the program goes to the next statement, which is else. In other words, the code is saying, 'If the if statement is true then do it, or else do what's in the else statement'. The else statement line just says that whatever value getDay returns will be assigned to the variable Today. Then the code goes to the document.write line for printing. These two statements can be very useful for all kinds of conditional branching, and are valuable tools for the programmer. They allow your code to make 'choices' according to conditions, like the answer a user may type into a form box. Now, if you will punch the button for our next example you will see an example of all the aforementioned functions. Here's the code that printed all of that:
<script language="JavaScript"> First of all, let me remind you that everything after the words 'document.write' goes on one single line. Dont use any text program that puts carriage returns in if wordwrap is turned on; I would recommend using either NoteTab or EditPad. If you're not sure about your text editor, then leave wordwrap off. Don't let the complexity of the above code confuse you; it's really pretty simple- there is just a lot of formatting text mixed in with the "javascript". The variable 'tellTime' is what I dreamed up to equal the 'new Date' function. You should be basically familiar with 'document.write' from Lesson 1, and the only thing that needs to be pointed out is that 'new Date' is not the same as 'getDate'. We want to be sure that when the button is punched that the new, or current date and time is accessed, and not some old value that may be stored in memory. Anyway, this is the correct form to use in order to get the current date and time. Well, we're about done with this lesson, but you've been so patient and studious (right?) that I'll give you this extra little script.
<script language="JavaScript"> Here's the output, depending on the time of day: About everything in the above code you have already basically been exposed to by now, so I won't go into a lot of detail. If you are wondering about the double ampersands (&&), think of them as meaning 'and' in this instance, meaning 'if both statements are true'. These are Operators, and we'll be getting to them later on.
In any programming language, once you get the basics, the rest of it is learned more by close and careful examination of the code, lots of practice in writing your own code, and maybe more than anything else, the time you spend trying to dig out the Go over the above code letter by letter and think about what each segment does. Copy and paste it into an html doc by itself and modify it, experiment with it and add to it and take parts of it out. Pay particular attention to the nesting of the parenthesis and quotes. Believe me, when you have the basics, you will learn more by doing this than by any effort on my part to teach you. Y2K Fix I mentioned earlier that we would talk about the 'getYear()' y2k bug, so here we go. The problem stems from the fact that getYear() just takes 1900 and adds the last two digits of the present year to that number to come up with the current year. Often, however, when it goes past 1999 and comes to 200, it returns the number 100 instead of what you might expect. It's been widely published that because of the getYear() bug that the simple solution is to use getFullYear() to solve the problem. Unfortunately, this will not solve the problem in more than a few browser versions because while getYear() is pretty well universally supported, getFullYear() is not. But don't despair; here is a fix that uses the more common getYear() method and makes the date come out right anyhow.
<script language="Javascript"> This is the output of the fix: That's about it for dates and time. If you expected a clock script in this lesson, then you must have skipped Lesson 5 on Functions; lots of people do that because they are a little intimidated by them. Anyway, that's where you'll find out how to make a "javascript" clock and find ways to use the real power of "javascript" using functions. Lesson 7 (1) (2) (3) (4) (5) (6) (7) (8) |