4

JavaScript Add Days to Date

 1 year ago
source link: https://masteringjs.io/tutorials/fundamentals/date-add-days
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JavaScript Add Days to Date

Jun 21, 2023

JavaScript Dates have a setDate() function that sets the current date of the month. This function handles rolling over months, so setDate(32) will increment the date's month and set the correct date. For example, here's how you can add 30 days to June 1, 2022.

const date = new Date('2022-06-01'); // June 1, 2022 UTC time

date.setDate(date.getDate() + 30); // Add 30 days
date; // July 1, 2022 UTC time

The setDate() function modifies the date object in-place and returns the new Unix timestamp as a number. So if you want to immediately use the date with a given number of days added, you can do the following:

const date = new Date('2022-06-01'); // June 1, 2022 UTC time

new Date(
  date.setDate(date.getDate() + 37)
); // July 8, 2022 UTC time

If you want to add days to the current day, and zero out the time components, you can use the setHours() function, which also allows you to modify the date's minutes, seconds, and milliseconds components.

const now = new Date();
// Add 37 days to now, and zero out hours, minutes, seconds, milliseconds
now.setDate(now.getDate() + 37);
now.setHours(0, 0, 0, 0);

Working with JavaScript dates can be inelegant because most date methods return timestamps, not dates, so chaining isn't possible. That's what common libraries, like date-fns and Luxon are for.

With date-fns

Date-fns has a neat add() function that lets you add dates to the current date.

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

// Returns a date instance representing July 8, 2022 UTC time.
add(new Date('2022-06-01'), { days: 37 });

With Luxon

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

// Returns a date instance representing July 8, 2022 UTC time.
DateTime.fromJSDate(new Date('2022-06-01')).plus({ days: 37 }).toJSDate();

More Fundamentals Tutorials


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK