JavaScript: Date Object Functionality

The built-in object for date and time in JavaScript is Date. It handles all functionality: creation, modification and, partially, date formatting.


  1. Constructors
  2. Getter methods
  3. Setter methods
    1. Auto-adjusting
    2. Numeric conversion, date diff
  4. Formatting
    1. Parsing from string, Date.parse

1. Constructors

The syntaxes to create a Date are:

1. new Date(): Creates a Date object with current date and time:

2. new Date(milliseconds): Creates a Date given the number of milliseconds passed from January 1, 1970 00:00:00, GMT+0. Note, millisecond is 1/1000 of second

3. new Date(datestring): If the single argument is a string. See Date.parse method for the format.

4. new Date(year, month [, day, hours, minutes, seconds, ms]): The date can be created given it’s components in the current time zone. For this format there should be at least two first arguments, next ones are optional.

Note that year should have 4-digits, and month starts with 0:

To create a date given it’s components in UTC time zone, use static method Date.UTC():


2. Getter methods

All access to date/time components is carried out through methods.

getFullYear() Get 4-digit year
getMonth() Get month, from 0 to 11.
getDay() Get the number of day in a week, from 0(Sunday) to 6(Saturday)
getDate() Get day, from 1 to 31
getDay() getHours(), getMinutes(), getSeconds(), getMilliseconds()

Get the corresponding components.

These methods work in local time zone.

There are UTC variants of these methods: getUTCFullYear(), getUTCMonth(), getUTCDay() etc.

If your time zone is not UTC, the code below should output different hours:

Also, there is a pair of special getters:

getTime(): Returns number of milliseconds passed from 1 Jan 1970, midnight. Exactly the same as used in new Date(milliseconds) constructor.

getTimezoneOffset(): Returns the difference between the local time and UTC time, in minutes. If the daylight saving is in effect, it is taken into account.


Create a function getWeekDay(date) which outputs current weekday short form: ‘Sun’, ‘Mon’, ‘Tue’, ‘Sat’.

Solution

Let’s put all possible day names in the array, and then get the appropriate element:

There are countries which use Monday as day 0, Tuesday as day 1 and so on, Sunday is last day 6.


Create a function getLocalDay(date) which returns day number in this representation.

Solution

The solution is given below:


3. Setter methods

The following methods allow to set date components:

  • setFullYear(year [, month, date])
  • setMonth(month [, date])
  • setDate(date)
  • setHours(hour [, min, sec, ms])
  • setMinutes(min [, sec, ms])
  • setSeconds(sec [, ms])
  • setMilliseconds(ms)
  • setTime(milliseconds) (sets whole date)

All of them except setTime() are available in UTC variants: setUTCHours().


Auto-adjusting

The important property of the Date object is that it accepts even incorrect components and auto-adjusts itself.

For example, let’s set 62 second:

Let’s increase the month for Dec, 2011:

What day of week will be 1000 days after today?


Write JavaScript to console.log that for you. The result should be a number from 0(Sunday) to 6(Saturday).

Solution

To get a date, 1000 days after today – simply add 1000 to the number of days:

The Date object auto-adjusts itself and gives the correct result.


Numeric conversion, date diff

The Date object when used as a primitive value, gets converted into it’s millisecond representation:

As a side effect, dates can be substracted, resulting in time difference. That’s used in measuring and profiling:


4. Formatting

Actually, there are several formatting methods in Date:

toString(), toDateString(), toTimeString()
The basic string representation. Formatting is not specified, it depends on the browser. Methods toDateString() and toTimeString() which stringify only date or only time part.
toLocaleString(), toLocaleDateString(), toLocaleTimeString()
Same as above, but applies system locale formatting and native language.
toUTCString()
Same as toString(), but returns string for UTC date.
toISOString()
Returns the date in ISO format, see details in string parsing section below:

Native Date formatting methods do not allow to specify custom format. So, function formatting functions are created instead.


Create function formatDate(d) which outputs date d in the format dd.mm.YY:

P.S. Make sure that leading zeroes are at place, so 1 Jan 2011 would become 01.01.11, not 1.1.11.

Solution

  1. The day is extracted by d.getDate(). To follow the format, days less than 10 are prepended with 0:

  2. d.getMonth() returns the month beginning from 0, so we need to increment it by one:

  3. The year is returned in 4-digit form. To make it 2-digit, use the modulo operator:

    >Note that the year just like other components needs to be left-padded with zero.

The full code:

Solution

The general scheme is to create a string: “

”, and then assign to innerHTML.

  1. Create d = new Date(year, month-1). It is set to the first day of the month.
  2. Fill the first row with empty cells, to show days before d.getDay()
  3. While d is at same month, increment it’s month day with d.setDate(d.getDate()+1) and add the cell into table.
  4. When the day is last in the week (check by d.getDay() % 7 == 6), split the table by adding " "
  5. Finish the table by empty cells.

See the detais below:


Parsing from string, Date.parse

Parsing from and to simplified ISO 8601 Extended format is implemented in most browsers excepts IE<9.

The format is: YYYY-MM-DDTHH:mm:ss.sssZ. The ‘Z’ part denotes an optional time zone. Subforms are also possible:

There is a method Date.parse(str) which parses the str into Date object.

If parsing fails, Date.parse returns NaN.

The example below works correctly in recent browsers except IE<9 which uses it's own non-standard format for Date.parse:

Prior to ECMAScript 5th edition, there were no Date string format, so browsers invented formats of their own.
The following older non-ISO format is accepted by all browsers including IE:

You can read more about other non-ISO variants supported by IE in MSDN Date.parse documentation and find the one you want to use. But you have to check the chosen format against all browsers, because it’s non-standard.


Resource: Javascript.info

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA