JavaScript Date Object

In JavaScript the Date object is used to get or set the year, month or day. The Date objects are created with the new Date() constructor. There are four ways to create a date object :

1. new Date() :

The new Date() creates  a new Date object with the current date and time. The syntax would be :
  var d = new Date();
Example :
<html>
<body>
  <script>
    var d = new Date();
    document.write(d);
  </script> 
</body>
</html>
Output :



2. new Date(milliseconds) :

The new Date(milliseconds) creates a new date object as zero time + provided milliseconds. Where the zero time means 01-January-1970. The syntax would be :
  var d = new Date(milliseconds);
Example :
<html>
<body>
  <script>  
    var d1 = new Date(0);
    document.write(d1);
    document.write("<br/>");
    var d2 = new Date(10000000000);
    document.write(d2);
  </script> 
</body>
</html>
Output :



3. new Date(dateString) :

The new Date(dateString) creates a new date object from a date string. The syntax would be :
  var d = new Date("date string");
Example :
<html>
<body>
  <script>
    var d = new Date("May 22, 2018 11:15:36");
    document.write(d);
  </script> 
</body>
</html>
Output :



4. new Date(year, month, day, hours, minutes, seconds, milliseconds) :

The new Date(year, month,....) method creates a new date object with a specified date and time. There are 7 parameters which specifies year, month, day, hours, minutes, seconds, milliseconds in that particular order. We can also omit the parameters from the back side (milliseconds), but atleast there are two parameters are available otherwise it treat is as a milliseconds. 

Example :
<html>
<body>
  <script>
    var d1 = new Date(2018, 01, 15, 12, 30, 45, 0);
    document.write(d1);
    document.write('<br/>');
    var d2 = new Date(2018, 01);
    document.write(d2);
  </script> 
</body>
</html>
Output :



Different Date formats :

Complete Date :
  var d = new Date("2018-05-25");
Year and Month :
  var d = new Date("2018-05");
Years Only :
  var d = new Date("2018");
Date-Time :
  var d = new Date("2018-05-25T12:00:00");
Where T separate the time from date.

Short Dates Format :
  var d1 = new Date("22/03/2015");
  var d2 = new Date("22-03-2015");
Long Dates Format :
 var d = new Date("May 22 2018");
 var d = new Date("22 May 2018");
 var d = new Date("May 22, 2018");


Next Topic :