When you print the date using `
console.log(date)`, you’ll get the current date and time.
There are several methods you can use with the Date object. The most common ones include:
getDate()`: returns the day of the month (from 1-31).
getDay()`: returns the day of the week (from 0-6).
getFullYear()`: returns the year.
getMonth()`: returns the month (from 0-11).
setDate()`: sets the day of the month for a specified date according to local time.
setFullYear()`: sets the full year for a specified date according to local time.
setMonth()`: sets the month for a specified date according to local time.
Determining Future Dates
1. Adding Days
In this code, date.getDate() gets the current day of the month, and we add seven to it, then date.setDate() sets the new day of the month.
2. Adding Months
Adding months to a date is similar to adding days. You can use the setMonth() and getMonth() methods:
In this code, date.getMonth() gets the current month, and we add three to it, then date.setMonth() sets the new month.
3. Adding Years
To add years to a date, use the setFullYear() and getFullYear() methods:
In this code, date.getFullYear() gets the current year, and we add five to it, then date.setFullYear() sets the new year.
Handling Edge Cases
To handle such edge cases, consider using a robust library like Moment.js or date-fns. These libraries provide more advanced and reliable date manipulation functions that handle these edge cases for you.
1. Using Moment.js
To use Moment.js, you first need to include it in your project. If you’re using Node.js, you can install it via npm:
For front-end applications, you can include it directly in your HTML:
Here’s how you can add days, months, or years to a date using Moment.js:
With Moment.js, the add() function takes care of all the edge cases and leap years, so you don’t have to worry about them.
2. Using date-fns
You can install date-fns in your Node.js application via npm:
Here’s how you can add days, months, or years to a date using date-fns:
With date-fns, the addDays(), addMonths(), and addYears() functions take care of all the edge cases and leap years for you.