Sunday, December 9, 2007

More date- functions

More date- functions

Now I want to show another example to you using the time and date methods. You already saw the lastModified property working. Now we are going to print the local time to our document. This method uses the time and date of your machine- so if you got the machine- date set to 5/17/1983 you will get the wrong date by this method as well. So this is not a time and date kept by the Internet (or something like that).

The following example prints out something like this. The time and date in the WWW- document is the real time and date (if the user has set the system- clock right of course).

The time now is: 0:13

The date is: 5/11/96

Here is the code:

At first we are creating a date variable. This is done by today=new Date(). If we do not specify a certain time and date the browser uses the local time and puts it into the variable today. Notice that we do not have to declare the variable today anywhere. This is a difference to Java and most other programming languages where you have to specify your types you want to use before you use them. We have created a time object which keeps the local time and date.

Now we can simply write its contents to the document. You have to write today before each get...- method. Otherwise the browser would not know which object to refer to. The getMonth() method returns a number between 0 and 11 (0 standing for january and 11 for december). So we have to add 1 to the number returned to get the right month. An interesting thing you could think of is to create a date - for example the date when you created a document. Then you could calculate how many days later somebody is reading your document. And if it is more than 10 days old you could tell him: Hey, this is really old- don't read it!

For this you will need the date of today as shown in the example above and the creation date. You can set a date while creating a date object. This would look like this:

docStarted= new Date(96,0,13)

You have to specify the year first, then the month (remember to decrease the month by one!) and then the day. You can also specify the time:

docStarted= new Date(96,0,13,10,50,0)

The first numbers are still the date. They are followed by the hour, the minutes and the seconds.

I have to tell you that JavaScript does not have a real date type. But as you see you can work with dates quite nice. This works because dates are represented by the number of milliseconds since 1/1/1970 0:0h. This sounds quite complicated but this is a common method for representing dates on computers. But you don't have to bother about this. You just have to care about the functions and this is not difficult at all. I just wanted to tell you so you don't think I tell you anything wrong.

No comments: