- Прибавить к дате день / месяц / год | JavaScript
- .toJSON и 00:00:00
- Add one month to date in javascript
- # Add Months to a Date in JavaScript
- # Add months to a Date without mutation
- # Add Months to a Date using date-fns
- # Add Months to a Date using moment.js
- # Additional Resources
- JavaScript: Add Month to a Date
- Add Months to a Date Value by Accessing Properties of a Date
- Frequently Asked:
- Add Months to a Date Value using setMonth()
- Related posts:
- Share your love
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
Прибавить к дате день / месяц / год | JavaScript
До 1 октября 33 дня или 1 месяц 3 дня (в сентябре 30 дней). Но скрипт считает что спустя 1 месяц 2 дня также наступит 1 октября.
var T = new Date(2016,7,29); T.setDate(T.getDate() + 2); // 31 августа T.setMonth(T.getMonth() + 1); // 1 октября var T = new Date(2016,7,29); T.setMonth(T.getMonth() + 1); // 29 сентября T.setDate(T.getDate() + 2); // 1 октября var T = new Date(2016,7,29); T.setDate(T.getDate() + 3); // 1 сентября T.setMonth(T.getMonth() + 1); // 1 октября var T = new Date(2016,7,29); T.setMonth(T.getMonth() + 1); // 29 сентября T.setDate(T.getDate() + 3); // 2 октября
Поскольку вначале прибавляется месяц, а затем число, так делать нежелательно:
+ лет + месяцев + дней =
.toJSON и 00:00:00
Нужно учитывать разницу между местным и UTC-временем. То есть не , а
Add one month to date in javascript
Last updated: Jan 13, 2023
Reading time · 4 min
# Add Months to a Date in JavaScript
To add months to a date:
- Use the getMonth() method to get a zero-based value for the month of the given date.
- Use the setMonth() method to set the month for the date.
- The setMonth method takes a zero-based integer for the month and sets the value for the date.
Copied!function addMonths(date, months) date.setMonth(date.getMonth() + months); return date; > // ✅ Add 2 months to the current Date const result1 = addMonths(new Date(), 2); console.log(result1); // 👉️ 2023-03-13T11:07:36.609Z // ---------------------------------------------- // ✅ Add 4 months to a different date const date = new Date('2023-04-14T00:00:00.000Z'); const result2 = addMonths(date, 4); console.log(result2); // 👉️ 2023-08-14T00:00:00.000Z
The addMonths function takes a Date object and N as parameters and adds N months to the date.
If you need to add months to the current date, call the Date() constructor without passing it any arguments.
Copied!function addMonths(date, months) date.setMonth(date.getMonth() + months); return date; > // ✅ Add 2 months to the current Date const currentDate = new Date(); const result1 = addMonths(currentDate, 2); console.log(result1); // 👉️ 2023-03-13T11:08:24.933Z
The Date.getMonth method returns an integer between 0 (January) and 11 (December), representing the month of the given date.
The setMonth() method takes a zero-based value representing the month of the year (0 = January, 1 = February, etc.) and sets the value for the date.
The JavaScript Date object automatically takes care of rolling over the year if adding X months to a date pushes us into the next year.
Copied!function addMonths(date, months) date.setMonth(date.getMonth() + months); return date; > // ✅ Add 13 months to a date const date = new Date('2023-04-14T00:00:00.000Z'); const result = addMonths(date, 13); console.log(result); // 👉️ 2024-05-14T00:00:00.000Z
We added 13 months to the date, which pushed us into the next year and the Date object automatically took care of updating the year.
# Add months to a Date without mutation
Note that the setMonth method mutates the Date object it was called on.
If you don’t want to change the Date in place, you can create a copy of it before calling the method.
Copied!function addMonths(date, months) const dateCopy = new Date(date); dateCopy.setMonth(dateCopy.getMonth() + months); return dateCopy; > const date = new Date('2023-04-14T00:00:00.000Z'); const result = addMonths(date, 5); console.log(result); // 👉️ 2023-09-14T00:00:00.000Z console.log(date); // 👉️ 2023-04-14T00:00:00.000Z
When a Date object is passed to the Date() constructor, it gets converted to a timestamp and can be used to create a copy of the date.
Mutating function parameters is a bad practice because calling the function with the same parameter multiple times returns different results.
Instead, pure functions like the one above return the same output when called with the same parameters.
You might see the setMonth method used with 2 parameters. The parameters the method takes are:
- month — a zero-based (0 = January, 1 = February, etc) value for the month of the year.
- day of the month (optional) — an integer from 1 to 31 that represents the day of the month.
The day of the month parameter is optional, and when not specified, the value returned from the getDate() method is used.
# Add Months to a Date using date-fns
You can also use date-fns module to add months to a date.
Copied!import addMonths> from 'date-fns'; const date = new Date('2023-04-14T00:00:00.000Z'); const result1 = addMonths(date, 1); console.log(result1); // 👉️ 2023-05-14T00:00:00.000Z const result2 = addMonths(date, 2); console.log(result2); // 👉️ 2023-06-14T00:00:00.000Z
The addMonths() function takes a date and the number of months to be added to the date as parameters.
The function doesn’t mutate the original date as shown in the example.
If you don’t have date-fns installed, you can install it by running the following command from your terminal.
Copied!# 👇️ create package.json if you don't have one npm init -y # ✅ install with NPM npm install date-fns # ✅ install with YARN yarn add date-fns
# Add Months to a Date using moment.js
You can also use the moment.js module to add months to a date.
Copied!import moment from 'moment'; const date = new Date('2023-04-14T00:00:00.000Z'); const result1 = moment(date).add(1, 'months'); console.log(result1); // 👉️ 2023-05-14T00:00:00.000Z const result2 = moment(date).add(2, 'months'); console.log(result2); // 👉️ 2023-06-14T00:00:00.000Z console.log(date); // 👉️ 2023-04-14T00:00:00.000Z
We used the moment().add() method to add months to a date.
The method can be used to add years, quarters, months, weeks, days, hours, minutes, seconds or milliseconds to a date.
If you don’t have moment installed, you can install it by running the following command from your terminal.
Copied!# 👇️ create package.json if you don't have one npm init -y # ✅ install with NPM npm install moment # ✅ install with YARN yarn add moment
The call to the add() method actually returns a moment object and not a native JavaScript date.
If you need to convert the value to a JavaScript date, use the toDate() method.
Copied!import moment from 'moment'; const date = new Date('2023-04-14T00:00:00.000Z'); const result1 = moment(date).add(1, 'months').toDate(); console.log(result1); // 👉️ 2023-05-14T00:00:00.000Z const result2 = moment(date).add(2, 'months').toDate(); console.log(result2); // 👉️ 2023-06-14T00:00:00.000Z console.log(date); // 👉️ 2023-04-14T00:00:00.000Z
The toDate() method takes care of converting the moment object to a native JavaScript Date object.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
JavaScript: Add Month to a Date
Date() constructor creates different date values. While working with dates in JavaScript, we often need to change the dates, like adding months to date before processing it. This article will discuss different ways to add months to a javascript date.
Add Months to a Date Value by Accessing Properties of a Date
Javascript’s getFullYear() will return the year of the date specified according to the local time .
Javascript’s getMonth() will return the mon th of the date specified according to the local time. The month value is zero-based that is zero indicates the first month of the year.
Javascript’s getDate() will return the day of the month of the date specified according to the local time.
Frequently Asked:
Add two months to today’s date
// function to add no of months to a date function addMonthsToDate(_date,_noOfMonths) < var yearFromDate = _date.getFullYear(); var monthFromYear = _date.getMonth(); var dayFromYear = _date.getDate(); var newDate = new Date(yearFromDate, monthFromYear + _noOfMonths, dayFromYear); return newDate; >//usage of the function addMonthsToDate var todayDate = new Date(); console.log("today's date: " + todayDate ) console.log("New Date: " + addMonthsToDate(todayDate,2));
Today's Date: Thu Feb 24 2022 23:21:10 GMT+0530 (India Standard Time) New Date: Sun Apr 24 2022 00:00:00 GMT+0530 (India Standard Time)
Explanation:-
- Here, we first get today’s date from the system using the new Date().
- Then we access different properties of the date.
- getFullYear() method gets the year from today’s date.
- getMonth() method receives the current month from today’s date.
- getDate() method receives the day from today’s date.
- After accessing all the above values, create a new date by Date() constructor, which sets the value of day and year based on how many months we are adding to the current month.
Add 13 months to today’s date
//function to add months to a date function addMonthsToDate(_date,_noOfMonths) < var yearFromDate = _date.getFullYear(); var monthFromYear = _date.getMonth(); var dayFromYear = _date.getDate(); var newDate = new Date(yearFromDate, monthFromYear + _noOfMonths, dayFromYear); return newDate; >//usage of the function addMonthsToDate var todayDate = new Date(); console.log("Today's Date: " + todayDate ) console.log("New Date: " + addMonthsToDate(todayDate,13));
Today's Date: Sat Feb 26 2022 18:20:23 GMT+0530 (India Standard Time) New Date: Sun Mar 26 2023 00:00:00 GMT+0530 (India Standard Time)
Add Months to a Date Value using setMonth()
Javascript’s setMonth() will set the month as per the specified date in accordance to the year which is set currently.
Add two months to today’s date
//function to add months to a date function addMonthsToDate(_date,_noOfMonths) < return new Date(_date.setMonth(_date.getMonth() + _noOfMonths)); >//usage of the function addMonthsToDate var todayDate = new Date(); console.log("Today's Date: " + todayDate ) console.log("New Date: " + addMonthsToDate(todayDate,2));
Today's Date: Sat Feb 26 2022 18:07:53 GMT+0530 (India Standard Time) New Date: Tue Apr 26 2022 18:07:53 GMT+0530 (India Standard Time)
Explanation:-
- Here, we first get today’s date from the system using the new Date().
- Access the current month according to the year of the date, using the getMonth() method.
- The new value of the month is set in the setMonth() method. The arguments passed in this method are the number of months received in the previous step added to the number of months we want to increase (2 in our case).
- Finally, the Date() constructor creates a new date with the values of the day, month and year decided by the number of months being added.
Add 13 months to today’s date
//function to add months to a date function addMonthsToDate(_date,_noOfMonths) < return new Date(_date.setMonth(_date.getMonth() + _noOfMonths)); >//usage of the function addMonthsToDate var todayDate = new Date(); console.log("Today's Date: " + todayDate ) console.log("New Date: " + addMonthsToDate(todayDate,13));
Today's Date: Sat Feb 26 2022 18:18:33 GMT+0530 (India Standard Time) New Date: Sun Mar 26 2023 18:18:33 GMT+0530 (India Standard Time)
I hope this article helped you add the number of months to a javascript date. Good Luck .
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.