JavaScript Dates

JavaScript Dates

In javascript, you should create Date object explicitly because there is no primitive Date data type. The Date object in Javascript is a built in Object that allows you to work with dates and times. Date objects are little bit complex but provide many useful methods for managing, comparing, and formatting dates. The numeric value for the Javascript Date object is the number of seconds since January 01, 1970 UTC. To create a Date object, using the new keyword together with the Date() constructor.

var today = new Date();

The above code will returned today's date and current time.

When using parameters with the Date object, follow the sequence of year, month, day, hours, minutes, seconds, and milliseconds.

var day = new Date(year, month, day, hours, minutes, seconds, milliseconds);

Once you've created a Date object using the new operator, there are lots of methods you can call from that object. Most of the methods you can use the get() methods to get values from a Date object and set() methods to set values to Date object.

Javascript Date methods

Javascript Date methods

The methods getDate(), getDay(), getMonth(), and getFullYear() allows you to retrieve date values from a Date object. Also setDate(), setMonth(), and setFullYear() methods enable you to set the date values of a Date object.

Important date() methods

getDay(): Returns the day of a Date object

getMonth(): Returns the month of a Date object

getFullYear(): Returns the year of a Date object

getYear(): Returns the year of a Date object using only two digits

getHours(): Returns the hours of a Date object

getMinutes(): Returns the minutes of a Date object

getSeconds(): Returns the seconds of a Date object

getTime(): Returns the number of milliseconds since midnight 1/1/1970

setMonth(): Sets the months in the Date object

setFullYear(): Sets the year in the Date object

setHours(): Sets the hours in the Date object

setMinutes(): Sets the minutes in the Date object

setSeconds(): Sets the seconds in the Date object

setTime(): Sets the milliseconds after 1/1/1970


var today = new Date(); alert(today.getFullYear());

The above code will return the current year.

var year = new Date(); year.setFullYear(2000, 01, 01); alert(year.getFullYear());

It will alert year 2000.

Date toString()

The toString() convert Date object to a string.

Date parse()

Javascript Date parse()

The parse() method returns a string date value that holds the number of milliseconds since January 01 1970 00:00:00

Date.parse('Jan 1, 2010')

It willreturned 12622884200000.