How to format a date in JavaScript

In JavaScript, you can work with dates and times using the built-in Date object. Here are some common tasks you might perform with the Date object:

Create a new date:

let date = new Date(); console.log(date); //Output: 2023-02-09T09:55:46.354Z
This creates a new Date object representing the current date and time.

Create a date from a specific time:

let date = new Date(2023, 1, 9, 12, 34, 56); console.log(date); //Output: 2023-02-09T12:34:56.000Z
This creates a new Date object with the specified year, month, day, hour, minute, and second.

It is important to note that months are 0-indexed in JavaScript, so January is represented as 0, February as 1, etc.

Access date components from the Date object

Following are the commonly used Access date components from the Date object.
let date = new Date();
Above code creates a new Date object representing the current date and time, and then uses the getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), and getSeconds() methods to extract the individual components of the date and time.
let date = new Date(); console.log(date); //Output: 2023-02-09T09:58:46.713Z
let year = date.getFullYear(); console.log(year); //Output: 2023
let month = date.getMonth(); console.log(month); //Output: 1
let day = date.getDate(); console.log(day); //Output: 9
let hours = date.getHours(); console.log(hours); //Output: 9
let minutes = date.getMinutes(); console.log(minutes); //Output: 58
let seconds = date.getSeconds(); console.log(seconds); //Output: 46

Setting date components in JavaScript

The JavaScript Date object provides several methods for setting the various components of a date and time, including the year, month, day, hour, minute, second, and millisecond. Explanation of each method:

setFullYear(year[, month[, date]])

This method sets the year component of a date. The year parameter is a 4-digit year (e.g. 2023). The month and date parameters are optional and specify the month (0-based, so January is 0) and day of the month, respectively.

setMonth(month[, date])

This method sets the month component of a date. The month parameter is a 0-based integer representing the month (so January is 0 and December is 11). The date parameter is optional and specifies the day of the month.

setDate(date)

This method sets the day of the month component of a date. The date parameter is an integer representing the day of the month.

setHours(hours[, minutes[, seconds[, ms]]])

This method sets the hour component of a date. The hours parameter is an integer representing the hour in 24-hour format. The minutes, seconds, and ms parameters are optional and represent the minute, second, and millisecond components of the time, respectively.

setMinutes(minutes[, seconds[, ms]])

This method sets the minute component of a date. The minutes parameter is an integer representing the minute. The seconds and ms parameters are optional and represent the second and millisecond components of the time, respectively.

setSeconds(seconds[, ms])

This method sets the second component of a date. The seconds parameter is an integer representing the second. The ms parameter is optional and represents the millisecond component of the time.

setMilliseconds(ms)

This method sets the millisecond component of a date. The ms parameter is an integer representing the millisecond.

The following example demonstrates how to use above methods to set the various components of a date and time:

let date = new Date(); date.setFullYear(2023); date.setMonth(0); // January date.setDate(9); date.setHours(0); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); console.log(date); //Output: 2023-01-09T00:00:00.000Z
Note that the Date object represents a specific moment in time in milliseconds since January 1, 1970 00:00:00 UTC, so be careful when setting the components to make sure the resulting date and time are valid.

Convert Date Formats in javascript


How do I format a date in JavaScript?
In JavaScript, you can convert between different date formats by creating a new Date object from an existing date string and then using the various methods of the Date object to retrieve the date components in the desired format.

Following are some examples of converting a date string in the format "YYYY-MM-DD" to different date formats:

Format JavaScript date as "MM/DD/YYYY"

let dateString = "2023-02-09"; let date = new Date(dateString); let month = (date.getMonth() + 1).toString().padStart(2, '0'); let day = date.getDate().toString().padStart(2, '0'); let year = date.getFullYear();
let newDateString = `${month}/${day}/${year}`; console.log(newDateString); //Output: 02/09/2023

Format JavaScript date as "DD-MM-YYYY"

let dateString = "2023-02-09"; let date = new Date(dateString); let month = (date.getMonth() + 1).toString().padStart(2, '0'); let day = date.getDate().toString().padStart(2, '0'); let year = date.getFullYear();
let newDateString = `${day}-${month}-${year}`; console.log(newDateString); //Output: 09-02-2023

Format JavaScript date as "DD MMM YYYY"

let dateString = "2023-02-09"; let date = new Date(dateString); let months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; let month = months[date.getMonth()]; let day = date.getDate().toString(); let year = date.getFullYear();
let newDateString = `${day} ${month} ${year}`; console.log(newDateString); //Output: 9 Feb 2023
By using the methods of the Date object, you can retrieve the various components of a date and time, and then use string concatenation and formatting to create a string in the desired format.

Get difference between 2 dates in JavaScript

You can calculate the difference between two dates in JavaScript by creating Date objects for each date, and then subtracting the time in milliseconds for the earlier date from the time in milliseconds for the later date. The difference will be the number of milliseconds between the two dates. You can then convert the result to a desired unit, such as days, hours, minutes, or seconds.

Calculate the number of days between two dates | JavaScript

let startDate = new Date("2022-12-01"); let endDate = new Date("2023-01-15"); let timeDiff = endDate.getTime() - startDate.getTime(); let dayDiff = Math.floor(timeDiff / (1000 * 3600 * 24)); console.log(`Number of days : ${dayDiff}`); //Output: Number of days : 45

In the above example, timeDiff is the difference in milliseconds between endDate and startDate, and dayDiff is the equivalent number of days (calculated by dividing timeDiff by the number of milliseconds in a day).

Note that the getTime() method returns the number of milliseconds since January 1, 1970 00:00:00 UTC for a given date, so subtracting the getTime() values for two dates will give you the difference between those dates in milliseconds.

JavaScript Date.now()

Date.now() is a static method of the JavaScript Date object that returns the number of milliseconds that have elapsed since January 1, 1970 00:00:00 UTC. This is often used as a more precise alternative to new Date().getTime(), which returns the same value.
let currentTime = Date.now(); console.log(currentTime);
The value returned by Date.now() can be used to calculate elapsed time or to create a new Date object representing the current date and time. For example:
let startTime = Date.now(); // Do some processing here let endTime = Date.now(); let elapsedTime = endTime - startTime; console.log(`Elapsed time: ${elapsedTime} milliseconds`);

Moment.js

Moment.js is a popular JavaScript library for working with dates and times. It provides a simple and intuitive API for parsing, validating, manipulating, and formatting dates and times in JavaScript. Most common tasks you can perform with Moment.js:

Parsing a date:

let date = moment("2022-12-01", "YYYY-MM-DD"); console.log(date);

Formatting a date:

let date = moment("2022-12-01", "YYYY-MM-DD"); console.log(date.format("MM/DD/YYYY"));

Adding and subtracting time:

let date = moment("2022-12-01", "YYYY-MM-DD"); console.log(date.add(7, 'days').format("YYYY-MM-DD"));

Comparing two dates:

let date1 = moment("2022-12-01", "YYYY-MM-DD"); let date2 = moment("2023-01-01", "YYYY-MM-DD"); console.log(date1.isBefore(date2));
The Moment.js library provides a wide range of methods and functions for working with dates and times, making it a useful tool for many types of applications.