Working with Dates and Time in JavaScript

Working with dates and time is very scary, I admit. Most of the time I retreat and find a library that can handle the details for me and avoid this topic at all costs. Besides libraries, JavaScript has a built-in class called Date which represents a point in time. And, if we like, we can use this class to work with dates and times.

To use this class we can either instantiate an object or work with its static methods. Let’s try the former approach first. As you probably know, to create an object we use the new keyword followed by the constructor, like this.

const now = new Date();

The above code creates a JavaScript object named now, and its value is the date/time at the moment of its creation. Furthermore, this object comes packed with a number of methods and properties we can use.

Also, besides creating a date/time object at that specific moment, you can pass an argument to the constructor and create the object at any point in time. For instance, to create a DateTime object when my son was born, I would do:-

const bdate = new Date(2020, 03, 28);
//Tue Apr 28 2020 00:00:00 GMT+0300 (East Africa Time)

Note that the second argument to the constructor is 03. But the month is April, that is because month counting starts from 0. We can also use other several ways of creating the object. Example:-

let bday = new Date('April 28, 2020')
let bday = new Date('April 28, 2020 00:00:00')
let bday = new Date(1588021200000)

As you see, all of the above create a date object at exactly the same point. Beware of the last example which uses a timestamp.

Using instance methods of Date to get the Date, Month and Time

To get the current year, month, day, and time we can simply call the instance methods of Date class. Let’s see some examples:-

const the_year = bday.getFullYear();
const the_month = bday.getMonth();
const [month, day, year] = [bday.getMonth(), bday.getDate(), bday.getFullYear()];

How to format the date into human readable format.

To format our date into human-readable format, we can use the toDateString, toLocalString, toLocalDateString etc. Let’s see each of these and their similar functions in action.

console.log(now.toDateString());//'Mon Nov 22 2021'
console.log(now.toLocalString());//'11/22/2021, 11:31:36 AM'
Your subscription could not be saved. Please try again.
Your subscription has been successful.

Learn Modern JS, CSS, & PHP

Subscribe to learn modern PHP in the most simple way.