Do you have any idea how the computer calculate the age of a person when input the birth date. For humans it is a easy task, because our brain can easily process it by calculating the year difference. But how the computer do it. For that we should input the date as a date object, where we separately say this is our year part, this is our month part and this is our day part and so on.. The Date object in JS lets you work with dates with years, months, days, minutes, seconds, milliseconds. Date objects are static, not dynamic. The computer time is ticking, but date objects, once created, are not.
Mon Oct 20 2014 10:24:36 GMT+0530 (Sri Lanka Standard Time)
Above shows the output of the code segment. When you display a date object in HTML, it is automatically converted to a string, with the toString() method. The toUTCString() method converts a date to a UTC string (a date display standard).
Mon, 20 Oct 2014 06:15:31 GMT
The toDateString() method converts a date to a more readable format.
Mon Oct 20 2014
Date objects are created with the new Date() constructor. There are 4 ways of initiating a date.
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Date methods let you get and set date values (years, months, days, minutes, seconds, milliseconds)
Date Get Methods
Get methods are used for getting a part of a date. Here are the most common (alphabetically).
|getDate()||Get the day as a number (1-31)|
|getDay()||Get the weekday a number (0-6)|
|getFullYear()||Get the four digit year (yyyy)|
|getHours()||Get the hour (0-23)|
|getMilliseconds()||Get the milliseconds (0-999)|
|getMinutes()||Get the minutes (0-59)|
|getMonth()||Get the month (0-11)|
|getSeconds()||Get the seconds (0-59)|
|getTime()||Get the time (milliseconds since January 1, 1970)|
Date Set Methods
Set methods are used for setting a part of a date. Here are the most common (alphabitically)
|setDate()||Set the day as a number (1-31)|
|setFullYear()||Set the year (optionally month and day yyyy.mm.dd)|
|setHours()||Set the hour (0-23)|
|setMilliseconds()||Set the milliseconds (0-999)|
|setMinutes()||Set the minutes (0-59)|
|setMonth()||Set the month (0-11)|
|setSeconds()||Set the seconds (0-59)|
|setTime()||Set the time (milliseconds since January 1, 1970)|
If you have an input value (or any string), you can use the Date.parse() method to convert it to milliseconds. Date.parse() returns the number of milliseconds between the date and January 1, 1970.
var msec = Date.parse(“March 21, 2012”)
The parameter of the parse method is not a date. It is just a string which says about a date where you cannot use it for any calculations. And we are converting that string into a actual date object, so we can do any date related calculations like as the follows.
var d = new Date(msec);
Dates can easily be compared with comparison operators.
someday > today