Wednesday, February 19, 2020

Date Object In JavaScript

Date Object In JavaScript

We can make displays and calculations related to dates with the help of inbuilt Date Objects in JavaScript. We can create a Date object using the Constructor Date().

Constructors for the Date Object are

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

new Date()

This constructor returns the current date and time string
<script>
  d=new Date();
  document.write(d);
</script>

Output:
Wed Feb 19 2020 14:37:31 GMT+0530 (India Standard Time)


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

This constructor returns the date and time( date, month, year, hours, minutes, seconds, etc) specified in the constructor.

<script>
  d=new Date(2020,1,19,14,45,55,33);
  document.write(d);
</script>


Output

Wed Feb 19 2020 14:45:55 GMT+0530 (India Standard Time)

The number of parameters can be varied according to the requirement.

<script>
  d=new Date(2020,1,19,14,45);
  document.write(d);
</script>

Output:
Wed Feb 19 2020 14:45:00 GMT+0530 (India Standard Time)

new Date(milliseconds)

JavaScript stores date as the number of milliseconds since January 01, 1970, 00:00:00 UTC (Universal Time Coordinated) that is considered as timestamp 0. To find the timestamp of a given date we can use Date(milliseconds), constructor.

<script>
  d=new Date(0);
  document.write(d);
</script>

Output:
Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)

The date string returned will be (Base time) 0 plus milliseconds added.
OR
<script>
  d=new Date(1579367877889);
  document.write(d);
</script>

Output:
Sat Jan 18 2020 22:47:57 GMT+0530 (India Standard Time)

new Date(date string)

We can create a new date object using the date string as well. A date string is a piece of text information about a timestamp formatted according to the standard Date objects in JavaScript.
<script>
  d=new Date('20 Feb 2020 10:23:33');
  document.write(d);
</script>

Output:
Thu Feb 20 2020 10:23:33 GMT+0530 (India Standard Time)

Getting information from Date Object

There are different methods available to access the components of the date object.


Output Method
Month (0 to 11) getMonth()
Year (the year 1900 is considered as 0)
getYear()
Date
getDate()
Day(0 to 6)
getDay()
  
Hours(0 to 23) getHours()
Minutes(0 to 59)
getMinutes()
Seconds(0 to 60)
getSeconds()





























For example,