Try my app Expense Manager @ google play and amazon store.

Thursday, June 28, 2012

Java Script Tutorial 21 : JavaScript Date Object


The JavaScript Date object is used to work with dates and times. Date objects are created with the Date() constructor. We can initiate date by four ways:

  • new Date()
  • new Date(milliseconds)
  • new Date(dateString)
  • new Date(year, month, day, hours, minutes, seconds, milliseconds)

We can operate a number of methods after creating a date object. These method allow you to get and set value of year, month, day, hour, minute, second, and milliseconds of the object. All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC) with a day containing 86,400,000 milliseconds.
For example


var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)


Set/Manipulate Dates :
We can easily manipulate the date by using the methods available for the Date object. For example


var myDateobj=new Date();
myDateobj.setFullYear(2011,0,15);


Adding days to a date shifts the month or year, the changes are handled automatically by the Date object itself.


Compare Two Dates :
We can also use Date object to compare two dates. For example


var y=new Date();
y.setFullYear(2110,0,16);
var current = new Date();
if  ( y > current )
   {
       alert("Current Date is before 16th January 2110");
   }
 else
   {
       alert("Current Date is after 14th January 2100");
   }

No comments:

Post a Comment

Follow by Email

Google+ Badge