Date/Time functions

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

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

Constructors

The syntaxes to create a Date are:

new Date()
Creates a Date object with current date and time:
var now = new Date()
alert(now)

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
// 24 hours after Jan 1, 1970
var Jan02_1970 = new Date(3600*24*1000) 
alert( Jan02_1970 )

new Date(datestring)
If the single argument is a string. See Date.parse method for the format.
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:

new Date(2011, 0, 1, 2, 3, 4, 567) // 1 Jan 2011, 02:03:04.567 in local timezone

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

Date.UTC(2011, 0, 1, 2, 3, 4, 567) // 1 Jan 2011, 02:03:04.567 in UTC

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:

var d = new Date()

alert( d.getHours() )
alert( d.getUTCHours() )

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.

alert( new Date().getTimezoneOffset() )  // For GMT-1 outputs 60

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

var date = new Date(2011,0,1))  // 1 Jan 2011 
alert( getWeekDay(date) )      // 'Sat'

Open solution
Solution

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

function getWeekDay(date) {
  var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']

  return days[ date.getDay() ]
}

var date = new Date(2011,0,1)  // 1 Jan 2011 
alert( getWeekDay(date) )      // 'Sat'

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.

var date = new Date(2011,0,1))  // 1 Jan 2011 
alert( getLocalDay(date) )      // Saturday, day 5

Open solution
Solution

The solution is given below:

function getLocalDay(date) {

  var day = date.getDay()

  if ( day==0 ) { // day 0 becomes day 7
    day = 7 
  }
  
  // day now is between 1(Monday) ... 7(Sunday) 

  return day - 1 // make it 0..6
}

alert( getLocalDay(new Date(2011,0,1)) )  // 5

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:

var d = new Date()
d.setSeconds(62)

alert(d)  // outputs correct date, increased by 1 min 2 sec.

Let’s increase the month for Dec, 2011:

var d = new Date(2011, 31)
d.setMonth( d.getMonth() + 1 )

alert(d)  // Jan, 2012

What day of week will be 1000 days after today?

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

Open solution
Solution

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

var d = new Date
d.setDate( d.getDate() + 1000 )

alert( d.getDay() )

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:

alert( +new Date ) // same as new Date().valueOf()

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

var start = new Date

for(var i=0; i<100000; i++) {
  var doSomething = i*i*i
}

var end = new Date

alert("Loop took "+(end-start)+" ms")

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.
var d = new Date()

alert( d.toString() ) // something like 'Wed Jan 26 2011 16:40:50 GMT+0300'
toLocaleString(), toLocaleDateString(), toLocaleTimeString()
Same as above, but applies system locale formatting and native language.
var d = new Date()

alert( d.toLocaleString() ) // date in your language and format
toUTCString()
Same as toString(), but returns string for UTC date.

var d = new Date()

alert( d.toUTCString() ) // something like 'Wed Jan 26 2011 13:42:28 GMT'

toISOString()
Returns the date in ISO format, see details in string parsing section below:

var d = new Date()

alert( d.toISOString() ) // something like '2011-01-26T13:51:50.417Z'

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:

var d = new Date(2011, 0, 30)  // 30 Jan 2011
alert( formatDate(d) )  // '30.01.11'

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

Open solution
Solution
  1. The day is extracted by d.getDate(). To follow the format, days less than 10 are prepended with 0:
    var dd = d.getDate()
    if (dd<10) dd= '0'+dd
    
  2. d.getMonth() returns the month beginning from 0, so we need to increment it by one:
    var mm = d.getMonth() + 1  // now moths are 1-12
    if (mm<10) mm= '0'+mm
    
  3. The year is returned in 4-digit form. To make it 2-digit, use the modulo operator:
    var yy = d.getFullYear() % 100
    if (yy<10) yy= '0'+yy
    

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

The full code:

function formatDate(d) {

  var dd = d.getDate()
  if ( dd < 10 ) dd = '0' + dd

  var mm = d.getMonth()+1
  if ( mm < 10 ) mm = '0' + mm

  var yy = d.getFullYear() % 100
  if ( yy < 10 ) yy = '0' + yy

  return dd+'.'+mm+'.'+yy
}

var d = new Date(2011, 0, 30)  // 30 Jan 2011
alert( formatDate(d) )  // '30.01.11'

Create a function to create a calendar table for given Year/Month.

First weekday is Sunday, last day - Saturday.

Every day (even empty) is represented by a TD. For example new Calendar("cal", 2011, 1) should fill the <div id='cal'></div> with calendar given below:

The starting document is here: tutorial/date/calendar_src.html

Open solution
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 "</tr><tr>"
  5. Finish the table by empty cells.

See the detais below:

function Calendar(id, year, month) { 
  var elem = document.getElementById(id)

  var mon = month - 1  // (1)
  var d = new Date(year, mon)
  
  var table = ['<table><tr>']

  // (2) fill first row 
  //  0  1  2  3  4  5  6
  // 29 30 31| 1  2  3  4  
  for (var i=0; i<d.getDay(); i++) {
    table.push('<td></td>')
  }
  
  // main body (3)
  while(d.getMonth() == mon) {
    table.push('<td>'+d.getDate()+'</td>')

    if (d.getDay() % 7 == 6) {   // (4)
      table.push('</tr><tr>')
    }
    
    d.setDate(d.getDate()+1)  
  }
  
  // (5) table tail
  for (var i=d.getDay(); i<7; i++) {
    table.push('<td></td>')
  }
  
  table.push('</tr></table>')

  elem.innerHTML = table.join('\n')
}

See the whole solution at tutorial/date/calendar.html

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:

YYYY 
YYYY-MM 
YYYY-MM-DD
THH:mm   // example: 'T12:00'
THH:mm:ss 
THH:mm:ss.sss

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:

var d = Date.parse('2011-01-26T13:51:50.417') 
// d = Date

alert(d)

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:

var d = Date.parse("January 26, 2011 13:51:50")

alert(d)

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.

Tutorial

Donate

Donate to this project