WebTuts - seomat.com

Your ultimate destination for comprehensive, easy-to-follow web tutorials.

Add a period of time to a Date in JavaScript

Adding a period of time to a date in JavaScript involves utilizing the Date object and manipulating it using the getTime() method.

Utilizing the Date object in JavaScript enables you to append a time period to a date. Below is an illustration demonstrating how this can be accomplished:

// Create a new Date object with the initial date
let initialDate = new Date('2023-10-19T00:00:00');

// Define the period of time you want to add (in milliseconds)
let timeToAdd = 1000 * 60 * 60 * 24; // Adding 1 day

// Add the period of time to the initial date
let newDate = new Date(initialDate.getTime() + timeToAdd);

// Display the new date
console.log(newDate);

In this example, the timeToAdd variable represents the number of milliseconds you want to add to the initial date. You have the flexibility to modify this value to include any preferred duration of time.

Using Moment.js

// Create a new Date object with the initial date
let initialDate = new Date('2023-10-19T00:00:00');

// Add a period of time to the initial date
let oneDay = moment.duration(1, 'd');
let newDate = moment(initialData).add(oneDay); // Adding 1 day

// Display the new date
console.log(newDate);

Using Luxon 3.x

const { DateTime } = require('luxon');

// Create a new Date object with the initial date
let initialDate = new Date('2023-10-19T00:00:00');

// Add a period of time to the initial date
let newDate = DateTime.fromJSDate(initialDate).plus({ days: 1 }).toJSDate(); // Adding 1 day

// Display the new date
console.log(newDate);

Using date-fns

const add = require('date-fns/add');

// Create a new Date object with the initial date
let initialDate = new Date('2023-10-19T00:00:00');

// Add a period of time to the initial date
let newDate = add(initialDate, { days: 1 }); // Adding 1 day

// Display the new date
console.log(newDate);