Home >Web Front-end >JS Tutorial >How Can I Add 30 Minutes to a JavaScript Date Object?
How to Increment a JavaScript Date Object by 30 Minutes
Adding 30 minutes to a Date object in JavaScript is a common task that can be accomplished in several ways.
Using a Library
For frequent date manipulation tasks, consider utilizing JavaScript date libraries such as Luxon, Day.js, or Moment.js. For instance, with Moment.js, you can simply code:
var newDateObj = moment(oldDateObj).add(30, 'm').toDate();
Vanilla JavaScript
Without relying on libraries, you can use the following method:
var newDateObj = new Date(oldDateObj.getTime() + diff*60000);
where diff represents the difference in minutes from oldDateObj's time. The multiplication by 60000 converts minutes to milliseconds.
As a reusable function:
function addMinutes(date, minutes) { return new Date(date.getTime() + minutes*60000); }
Caution with Vanilla JavaScript
Be aware that working with dates in vanilla JavaScript can be intricate. For instance, adding 24 hours to a date may not result in tomorrow's date in some scenarios. This is why it's advisable to utilize a library if extensive date manipulation is necessary.
Below is a more versatile function that adheres to MySQL's DATE_ADD syntax:
function dateAdd(date, interval, units) { if(!(date instanceof Date)) return undefined; var ret = new Date(date); //don't change original date var checkRollover = function() { if(ret.getDate() != date.getDate()) ret.setDate(0);}; switch(String(interval).toLowerCase()) { // ... (remaining code snippet) } return ret; }
This function allows for adding different time intervals (e.g., years, hours, seconds) to a date object.
The above is the detailed content of How Can I Add 30 Minutes to a JavaScript Date Object?. For more information, please follow other related articles on the PHP Chinese website!