Add or subtract days from a Date object

Function

		/** 
		 * @description add or subtract days from a date
		 * @param {Date} oDate - starting date
		 * @param {integer} iDays - number of days to add/subtract
		 * @param {boolean} bSubtract - subtract or add days
		 * @returns {Date} changed date
		 */
		changeDaysofDate: function(oDate, iDays, bSubtract) {
			var oNewDate = new Date(oDate);

			if (bSubtract) {
				oNewDate.setDate(oNewDate.getDate() - iDays);
			} else {
				oNewDate.setDate(oNewDate.getDate() + iDays);
			}

			return oNewDate;

		}

Example

new Date();
//Expected output: Tue Jun 27 2023 15:21:32 GMT+0200
this.changeDaysofDate(new Date(), 1, true);
//Expected output: Mon Jun 26 2023 15:20:42 GMT+0200
this.changeDaysofDate(new Date(), 1, false);
//Expected output: Wed Jun 28 2023 15:20:53 GMT+0200

Related Information

Leave a Reply

Your email address will not be published. Required fields are marked *