Javascript date object demo

The JavaScript provides a date object which can be used to display date and time.

We can either create a date object with the empty Date() constructor or another three overload versions of the Date constructors as listed below.

var todate = new Date(milliseconds);  
var todate = new Date(dateString);  
var todate = new Date(year, month, day, hour, minutes, seconds, milliseconds)  

After we have created the date object we can then use it’s method to get month, time, date or year.

var today = new Date(); // create a new date object

console.log(today.getFullYear()); // return 2018

console.log(today.getMonth()); // return month in the numerical value, for example January is 0

console.log(today.getDate()); // return today date

console.log(today.getDay()); // return day in the numerical value, for example, Saturday is 6

console.log(today.getHours()); // return hours

console.log(today.getMinutes()); // return minutes

console.log(today.getMilliseconds()); // return milliseconds

console.log(today.getSeconds()); // return seconds

console.log(today.getTime()); // returns the number of milliseconds between midnight of the January 1, 1970 and the 
                              // specified date

If we are using one of the optional constructor to create a date object then we can set the year, month as well as date and time. For example,

var todate = new Date("January 1, 2019"); // take in a date string object as it's parameter

Date object is very useful for us to display date and time on our website. That is it for the javascript date object, let move on to the next topic.

Leave a Reply

Be the First to Comment!

Notify of