Online Documentation Server
 ПОИСК
ods.com.ua Web
 КАТЕГОРИИ
Home
Programming
Net technology
Unixes
Security
RFC, HOWTO
Web technology
Data bases
Other docs

 


 ПОДПИСКА

 О КОПИРАЙТАХ
Вся предоставленная на этом сервере информация собрана нами из разных источников. Если Вам кажется, что публикация каких-то документов нарушает чьи-либо авторские права, сообщите нам об этом.




Previous Table of Contents Next

Chapter 14
Time and Date in JavaScript

The Date Object

JavaScript includes a Date object, borrowed from Java. If you are familiar with other modern programming languages, you probably recall that time and date are stored in explicit type data structures. As explained in Chapter 13, JavaScript tends to implement as many language features as possible. Both dates and times in JavaScript are derived from the Date object, which includes a rich set of methods related to derivation of dates and times.

JavaScript treats the Date object like a constructor class. To implement the current date or time in your script you must first create a new instance of the object. You can then extract the desired data from that particular instance.

The Date object has quite a misleading name because it also includes methods strictly for dealing with time values.

JavaScript handles dates similarly to Java. Many methods are implemented in both languages, resulting in an observable parallelism. All dates are stored as the number of milliseconds since January 1, 1970, 00:00:00.

Creating a Date Instance

Many JavaScript programmers, including book authors, often confuse object-related nomenclature when computing date and time elements as the creation of a Date object. The Date object is a single built-in object, by which you can create instances to store encoded data related to the date and time of a certain moment. The Date object is built in, just like the Array object discussed in depth in the previous chapter. It acts as a template when creating instances of the object. The most basic assignment statement regarding the Date object is obviously the one that creates an instance according to the default arguments:

var dateInstance = new Date()

This statement simply assigns an instance of the Date object to the data structure named dataInstance. Take a look at the following script:

var now = new Date()
alert(now)

According to the current time of the operation, the output of the script resembles the following:


Figure 14-1.  An instance of the date object can be displayed to show the current time.

Although now is an identifier of an instance of the date object, it holds a partial string value at its highest level. That is, if you try to print its value it appears to be a string. However, because it does not belong to the explicit String object, string properties and methods do not apply to it. For example, the following script generates an error because split() is a method of strings only:

var nowDate  = new Date()
var nowArray = new Array()
nowArray = nowDate.split(" ")

You can slightly modify this script to work in the following form:

var nowDate  = new Date()
var nowArray = new Array()
var nowString = new String(nowDate)
// or: var nowString = nowDate + ""
// or: var nowString = nowDate.toString()
nowArray = nowDate.split(" ")
alert(nowArray.join(" ; "))

The script’s output is:


Figure 14-2.  An instance of the Date object can be processed at its highest level by converting it to a string.

Notice that there are two semicolons near the end of the string. You will see later that the time zone is specified between them.

If you want to refer to an instance of the Date object as a string, it is safer to convert it to a string, explicitly:

var newObj = new Date()
var str = newObj.toString() // toString method explained later

Parameters of the Date Constructor

Until now we created instances of the Date object without any arguments; that is, we built the instances according to the default arguments. The default is the current date and time on the client’s machine. JavaScript enables you to create Date instances of specific dates, which you can later use with date arithmetic.

Whenever you provide arguments to Date, pay attention to the following computation algorithms:

  • Computers store all dates as the number of milliseconds since January 1, 1970, 00:00:00. As a result, if you try to create an instance of the Date object specifying a date before January 1, 1970, 00:00:00, it will probably cause the browser to crash. It is not known yet if and when Netscape and Microsoft will fix this bug in their browsers. Until then, you should always use dates after this 1970 date. If the user is prompted to enter a date, it must be verified so an improper date does not cause the browser to crash. This bug is expected to be solved, or at least modified to return an error whenever you assign such values, but for now you will see an annoying message as the browser crashes under such operations:


    Figure 14-3.  Despite the message, don't call the vendor because this is a known bug. Note that the bug will persist!

  • Similar to the previous bug, some versions of Netscape Navigator crash if you create an instance with a date after 1999. This may seem much more problematic than the pre-1970 bug, because this year is coming closer every day. You have probably heard predictions regarding the computerized world after the year 2000 due to the fact that all two-digit year specifications will have to be fixed. Although the year 2000 may still seem far away (unless you are reading this book after 2000 or a year before), it is important that you make your scripts compatible with future situations. Luckily for us, there is a workaround for this problem: Create such dates with numeric arguments instead of the more intuitive string format. Note also that this bug exists in Netscape Navigator 2.0 but is apparently fixed in Navigator 3.0.

You can use an argument of the following format to create a date other than the current one:

Month day, year hours:minutes:seconds

Here is an example that creates an instance of a date that occurred in the past:

var Xmas95 = new Date("December 25, 1995 13:30:00")

You can also create an instance according to a set of integers of the following format:

year, month, day, hour, minute, seconds

Here is an example using this format:

var Xmas95 = new Date(95,11,25,9,30,0)

One important concept is the requirement of year, month, and day specification in both formats (string and integers). If you omit the hours, minutes, or seconds they are set by default to zero. Nonetheless, omitting any of the first three arguments results in an error and even crashes the browser under some operating systems.

Previous Table of Contents Next


With any suggestions or questions please feel free to contact us