< JavaScript

A Date is an object that contains a given time to millisecond precision.

Unlike strings and numbers, the date must be explicitly created with the new operator.

var date = new Date(); // Create a new Date object with the current date and time.

The Date object may also be created using parameters passed to its constructor. By default, the Date object contains the current date and time found on the computer, but can be set to any date or time desired.

var time_before_2000 = new Date(1999, 12, 31, 23, 59, 59, 999);

The date can also be returned as an integer. This value can be used to "seed" a PRNG (Pseudo Random Number Generator) method, for example.

var integer_date = +new Date; // Returns a number, like 1362449477663.

The date object normally stores the value within the local time zone. If UTC is needed, there are a set of functions available for that use.

The Date object does not support non-CE epochs, but can still represent almost any available time within its available range.

Properties and methods

Properties and methods of the Date() object:

  • getDate(): Returns the day of the month. [1 - 31][1]
  • getDay(): Returns the day of the week within the object. [0 - 6]. Sunday is 0, with the other days of the week taking the next value.
  • getFullYear(): Retrieves the full 4-digit year within the Date object.
  • getMonth(): Returns the current month. [0 - 11][2]
  • getHours(): Returns hours based on a 24 hour clock.[3]
  • getMinutes():Returns minutes based on [0 - 59][4]
  • getSeconds():Returns seconds based on [0 - 59][5]
  • getTime(): Gets the time in milliseconds since January 1, 1970.
  • parse(text): Reads the string text, and returns the number of milliseconds since January 1, 1970.
  • setFullYear(year): Stores the full 4-digit year within the Date object.
  • setMonth(month, day): Sets the month within the Date object, and optionally the day within the month. [0 - 11]. The Date object uses 0 as January instead of 1.
  • Date.now(): Gets the current date and time.

Further Reading

  1. https://www.w3schools.com/js/js_date_methods.asp
  2. https://www.w3schools.com/js/js_date_methods.asp
  3. https://www.w3schools.com/js/js_date_methods.asp
  4. https://www.w3schools.com/js/js_date_methods.asp
  5. https://www.w3schools.com/js/js_date_methods.asp
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.