DEV Community

Cover image for How to use the built-in Date Object to Get the Current Date in JavaScript?
evenmik
evenmik

Posted on

How to use the built-in Date Object to Get the Current Date in JavaScript?

When you are building a website, you will come across various types of date components-- it could be to create a date of a resource or the timestamp of an activity.

Handling these date and timestamp formatting can be a daunting process. Read on to understand how you can get the current date in different formats in JavaScript.

JavaScript's Date Object

The built-in Data object stores the date & time while providing methods for handling them.

You have to use the new keyword to build a new instance of the Date object:

const date = new Date();

There are methods for getting the current year and current day of the month, have a look at it:

For year:

const currentYear = date.getFullYear();
console.log(currentYear);

For day of the month:

const today = date.getDate();
const currentMonth = date.getMonth() + 1;

Date Now

now() is a static method of the Date object. This is how it is used:

const timeElapsed = Date.now();
const today = new Date(timeElapsed);

Formatting The Date

To format the date into several different formats like ISO, GMT, you can make use of the methods if the Date object.

The toDateString() method returns the date in a human readable format:

today.toDateString();

The toISOString() method returns the date which follows the ISO 8601 Extended Format:

today.toISOString();

The toUTCString() method returns the date in UTC timezone format:

today.toUTCString();

and so on.

Custom Date Formatter Function

Your date could be in yy/dd/mm or yyyy-dd-mm format. To get rid of the uncertainty, it might be beneficial for you to build a reusable function so that it can be used across multiple projects.

const today = new Date();

function formatDate(date, format) {
//
}

formatDate(today, 'mm/dd/yy');

You need to replace the strings "mm", "dd", "yy" with the desired month, day and year values from the format string passed in the argument.

To do that you can use the replace() method like shown below:

format.replace('mm', date.getMonth() + 1);

Top comments (0)