Using a Library

If you are doing a lot of date work, you may want to look into JavaScript date libraries like Luxon, Day.js, or Moment.js. For example, with Moment.js, this is simply:

var newDateObj = moment(oldDateObj).add(30, 'm').toDate();

Vanilla Javascript

This is like chaos's answer, but in one line:

var newDateObj = new Date(oldDateObj.getTime() + diff*60000);

Where diff is the difference in minutes you want from oldDateObj's time. It can even be negative.

Or as a reusable function, if you need to do this in multiple places:

function addMinutes(date, minutes) {
    return new Date(date.getTime() + minutes*60000);
}

And just in case this is not obvious, the reason we multiply minutes by 60000 is to convert minutes to milliseconds.

Be Careful with Vanilla Javascript. Dates Are Hard!

You may think you can add 24 hours to a date to get tomorrow's date, right? Wrong!

addMinutes(myDate, 60*24); //DO NOT DO THIS

It turns out, if the user observes daylight saving time, a day is not necessarily 24 hours long. There is one day a year that is only 23 hours long, and one day a year that is 25 hours long. For example, in most of the United States and Canada, 24 hours after midnight, Nov 2, 2014, is still Nov 2:

const NOV = 10; //because JS months are off by one...
addMinutes(new Date(2014, NOV, 2), 60*24); //In USA, prints 11pm on Nov 2, not 12am Nov 3!

This is why using one of the afore-mentioned libraries is a safer bet if you have to do a lot of work with this.

Below is a more generic version of this function that I wrote. I'd still recommend using a library, but that may be overkill/impossible for your project. The syntax is modeled after MySQL DATE_ADD function.

/**
 * Adds time to a date. Modelled after MySQL DATE_ADD function.
 * Example: dateAdd(new Date(), 'minute', 30)  //returns 30 minutes from now.
 * https://stackoverflow.com/a/1214753/18511
 * 
 * @param date  Date to start with
 * @param interval  One of: year, quarter, month, week, day, hour, minute, second
 * @param units  Number of units of the given interval to add.
 */
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()) {
    case 'year'   :  ret.setFullYear(ret.getFullYear() + units); checkRollover();  break;
    case 'quarter':  ret.setMonth(ret.getMonth() + 3*units); checkRollover();  break;
    case 'month'  :  ret.setMonth(ret.getMonth() + units); checkRollover();  break;
    case 'week'   :  ret.setDate(ret.getDate() + 7*units);  break;
    case 'day'    :  ret.setDate(ret.getDate() + units);  break;
    case 'hour'   :  ret.setTime(ret.getTime() + units*3600000);  break;
    case 'minute' :  ret.setTime(ret.getTime() + units*60000);  break;
    case 'second' :  ret.setTime(ret.getTime() + units*1000);  break;
    default       :  ret = undefined;  break;
  }
  return ret;
}

Working jsFiddle demo.

Answer from Kip on Stack Overflow
🌐
date-fns
date-fns.org
date-fns - modern JavaScript date utility library
date-fns provides the most comprehensive yet simple and consistent toolset for manipulating JavaScript dates in a browser & Node.js.
🌐
CodeSandbox
codesandbox.io › s › date-fns-addminutes-4qcpm
date-fns/addMinutes - CodeSandbox
November 16, 2021 - date-fns/addMinutes using @babel/runtime, date-fns
Published   Nov 16, 2021
Top answer
1 of 16
1366

Using a Library

If you are doing a lot of date work, you may want to look into JavaScript date libraries like Luxon, Day.js, or Moment.js. For example, with Moment.js, this is simply:

var newDateObj = moment(oldDateObj).add(30, 'm').toDate();

Vanilla Javascript

This is like chaos's answer, but in one line:

var newDateObj = new Date(oldDateObj.getTime() + diff*60000);

Where diff is the difference in minutes you want from oldDateObj's time. It can even be negative.

Or as a reusable function, if you need to do this in multiple places:

function addMinutes(date, minutes) {
    return new Date(date.getTime() + minutes*60000);
}

And just in case this is not obvious, the reason we multiply minutes by 60000 is to convert minutes to milliseconds.

Be Careful with Vanilla Javascript. Dates Are Hard!

You may think you can add 24 hours to a date to get tomorrow's date, right? Wrong!

addMinutes(myDate, 60*24); //DO NOT DO THIS

It turns out, if the user observes daylight saving time, a day is not necessarily 24 hours long. There is one day a year that is only 23 hours long, and one day a year that is 25 hours long. For example, in most of the United States and Canada, 24 hours after midnight, Nov 2, 2014, is still Nov 2:

const NOV = 10; //because JS months are off by one...
addMinutes(new Date(2014, NOV, 2), 60*24); //In USA, prints 11pm on Nov 2, not 12am Nov 3!

This is why using one of the afore-mentioned libraries is a safer bet if you have to do a lot of work with this.

Below is a more generic version of this function that I wrote. I'd still recommend using a library, but that may be overkill/impossible for your project. The syntax is modeled after MySQL DATE_ADD function.

/**
 * Adds time to a date. Modelled after MySQL DATE_ADD function.
 * Example: dateAdd(new Date(), 'minute', 30)  //returns 30 minutes from now.
 * https://stackoverflow.com/a/1214753/18511
 * 
 * @param date  Date to start with
 * @param interval  One of: year, quarter, month, week, day, hour, minute, second
 * @param units  Number of units of the given interval to add.
 */
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()) {
    case 'year'   :  ret.setFullYear(ret.getFullYear() + units); checkRollover();  break;
    case 'quarter':  ret.setMonth(ret.getMonth() + 3*units); checkRollover();  break;
    case 'month'  :  ret.setMonth(ret.getMonth() + units); checkRollover();  break;
    case 'week'   :  ret.setDate(ret.getDate() + 7*units);  break;
    case 'day'    :  ret.setDate(ret.getDate() + units);  break;
    case 'hour'   :  ret.setTime(ret.getTime() + units*3600000);  break;
    case 'minute' :  ret.setTime(ret.getTime() + units*60000);  break;
    case 'second' :  ret.setTime(ret.getTime() + units*1000);  break;
    default       :  ret = undefined;  break;
  }
  return ret;
}

Working jsFiddle demo.

2 of 16
373
var d1 = new Date (),
    d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 30 );
alert ( d2 );
🌐
W3cubDocs
docs.w3cub.com › date_fns › addMinutes
addMinutes - Date-fns - W3cubDocs
// ES 2015 import addMinutes from 'date-fns/addMinutes' ... // Add 30 minutes to 10 July 2014 12:00:00: const result = addMinutes(new Date(2014, 6, 10, 12, 0), 30) //=> Thu Jul 10 2014 12:30:00
🌐
Tabnine
tabnine.com › home page › code › javascript › date-fns
date-fns.addMinutes JavaScript and Node.js code examples | Tabnine
const currentDate = new Date() return faker.date.between(addMinutes(currentDate, 1), addMinutes(currentDate, 60))
🌐
GitHub
github.com › date-fns › date-fns › issues › 1517
addMinutes behavior with floats · Issue #1517 · date-fns/date-fns
October 30, 2019 - Currently addMinutes(d, 2.9) behaves like addMinutes(d, 2) which is unintuitive to say the least. Expected behavior to me would be the same as addMilliseconds(d, 2.9 * 60 * 1000). Alternatively it should throw an error. At the very least...
Author   NaridaL
🌐
GitHub
github.com › date-fns › date-fns › blob › main › src › addMinutes › index.ts
date-fns/src/addMinutes/index.ts at main · date-fns/date-fns
* Add the specified number of minutes to the given date. * * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
Author   date-fns
Find elsewhere
🌐
Runkit
runkit.com › devbyrayray › how-to-add-or-subtract-hours-minutes-or-seconds-from-a-date-in-javascript-with-date-fns
How To Add or Subtract Hours, Minutes, or Seconds from a ...
// import isn't supported in Node v18.11.0 otherwise it would be // import { addSeconds, subSeconds, addMinutes, subMinutes, addHours, subHours } from 'date-fns' const dateFns = require( "date-fns"); const { addSeconds, subSeconds, addMinutes, subMinutes, addHours, subHours } = dateFns; // 31th of January 2023 const date = new Date(2023, 0, 31, 10, 18, 35); console.log(date); console.log('Add 15 seconds: ', addSeconds(date, 15)); console.log('Subtract 2 seconds: ', subSeconds(date, 2)); console.log('Add 15 minutes: ', addMinutes(date, 15)); console.log('Subtract 2 minutes: ', subMinutes(date, 2)); console.log('Add 15 hours: ', addHours(date, 15)); console.log('Subtract 2 hours: ', subHours(date, 2));
🌐
Bit
bit.cloud › date-fns › date-fns › add-minutes
date-fns / add-minutes
Compose high-quality professional software with AI for simplicity, speed and control.
🌐
Envato Tuts+
code.tutsplus.com › home › javascript
Using date-fns for Easy Date Manipulation | Envato Tuts+
July 28, 2023 - Use the h or hh placeholders to ... minutes, and a for the AM/PM indicator. For example: There are many placeholders you can use to format dates and times. Some are listed in the following table, but be sure to visit the documentation for the ...
Top answer
1 of 8
82

According to the example code in date-fns/date-fns#229 (comment), we can now use intervalToDuration to convert seconds (passed as an Interval) to a Duration, which can then simplify formatting as desired by the OP:

import {  intervalToDuration } from 'date-fns'

const seconds = 10000

intervalToDuration({ start: 0, end: seconds * 1000 })
// { hours: 2, minutes: 46, seconds: 40 }

So for the OP's needs:

import {  intervalToDuration } from 'date-fns'

const seconds = 1807
const duration = intervalToDuration({ start: 0, end: seconds * 1000 })
// { minutes: 30, seconds: 7 }

const formatted = `${duration.minutes}:${duration.seconds}`
// 30:7

Edit (2022-08-04): It was pointed out that the above simplistic code won't 0-pad the numbers, so you will end up with 30:7 rather than 30:07. This padding can be achieved by using String.prototype.padStart() as follows:

import {  intervalToDuration } from 'date-fns'

const seconds = 1807
const duration = intervalToDuration({ start: 0, end: seconds * 1000 })
// { minutes: 30, seconds: 7 }

const zeroPad = (num) => String(num).padStart(2, '0')

const formatted = `${zeroPad(duration.minutes)}:${zeroPad(duration.seconds)}`
// 30:07

It was also pointed out that if the Interval goes above 60 minutes it will start incrementing the hours within the Duration, which the above code wouldn't display. So here is another slightly more complex example that handles this as well as the zeroPad case:

import {  intervalToDuration } from 'date-fns'

const seconds = 1807
const duration = intervalToDuration({ start: 0, end: seconds * 1000 })
// { minutes: 30, seconds: 7 }

const zeroPad = (num) => String(num).padStart(2, '0')

const formatted = [
  duration.hours,
  duration.minutes,
  duration.seconds,
]
.filter(Boolean)
.map(zeroPad)
.join(':')
// 30:07

There is also an issue on GitHub asking how to use a custom format with formatDuration, which suggest that currently the only way to do so is by providing a custom Locale. GitHub user @marselmustafin provided an example using this workaround. Following this same pattern, we could implement the OP's desired functionality roughly as follows:

import { intervalToDuration, formatDuration } from "date-fns";

const seconds = 1807;
const duration = intervalToDuration({ start: 0, end: seconds * 1000 });
// { minutes: 30, seconds: 7 }

const zeroPad = (num) => String(num).padStart(2, "0");

const formatted = formatDuration(duration, {
  format: ["minutes", "seconds"],
  // format: ["hours", "minutes", "seconds"],
  zero: true,
  delimiter: ":",
  locale: {
    formatDistance: (_token, count) => zeroPad(count)
  }
});
// 30:07
2 of 8
39

Here's the simple implementation:

import { formatDistance } from 'date-fns'

const duration = s => formatDistance(0, s * 1000, { includeSeconds: true })

duration(50) // 'less than a minute'
duration(1000) // '17 minutes'

This is basically the same as:

import moment from 'moment'    

const duration = s => moment.duration(s, 'seconds').humanize()

duration(50) // 'a minute'
duration(1000) // '17 minutes'
🌐
Reddit
reddit.com › r/reactjs › get remaining days,hours,minutes seconds to date with date-fns
r/reactjs on Reddit: Get remaining days,hours,minutes seconds to date with date-fns
March 25, 2022 -

I want to get remaining full countdown of next instance of weekday (for example next thursday), I have two functions:

FIRST: gets instance of next thursday

SECOND: calculates remaining days,hours,minutes and seconds

I first tried with moment.js but minutes and secodns always return 59 no matter what, days and hours seem to work.

So since moment is deprecated I need to do this wth date-fns which I don't know much about.

Please help me!

let nextThursday = getNextThursday();
        console.log('nextThursday',nextThursday);
LOG nextThursday "2022-03-22T14:30:31.514Z
        getCountdown(nextThursday);
 LOG Days:  2
 LOG  Hours:  23
 LOG  Minutes:  59
 LOG  Seconds:  59

const getCountdown = (ending) => {
    var now = moment();
    var end = moment(ending); // another date
    var duration = moment.duration(end.diff(now));
    
    console.log(end.diff(now))
  
    //Get Days and subtract from duration
    var days = duration.days();
    duration.subtract(days, 'days');
  
    //Get hours and subtract from duration
    var hours = duration.hours();
    duration.subtract(hours, 'hours');
  
    //Get Minutes and subtract from duration
    var minutes = duration.minutes();
    duration.subtract(minutes, 'minutes');
  
    //Get seconds
    var seconds = duration.seconds();
    console.log("Days: ", days);
    console.log("Hours: ", hours);
    console.log("Minutes: ", minutes);
    console.log("Seconds: ", seconds);
  };
 LOG  Minutes:  59
 LOG  Seconds:  59
const getNextThursday = () => {
        const dayINeed = 4; // for thursday
        const today = moment().isoWeekday();

        // if we haven't yet passed the day of the week that I need:
        if (today <= dayINeed) { 
        // then just give me this week's instance of that day
           return moment().isoWeekday(dayINeed);
        } else {
         // otherwise, give me *next week's* instance of that same day
           return moment().add(1, 'weeks').isoWeekday(dayINeed).utcOffset(0).set({hour:0,minute:0,second:0,millisecond:0});
           //return moment().add(1, 'weeks').add(22, 'minutes').add(43, 'seconds').isoWeekday(dayINeed);
        }
};
🌐
Stack Overflow
stackoverflow.com › questions › 67652124 › how-to-write-a-function-that-can-add-hours-and-days-correctly-to-the-target-time
How to write a function that can add hours and days correctly to the target time zone with date-fns?
import { add, Duration, parseISO } from "date-fns"; import { utcToZonedTime, format as formatTz } from "date-fns-tz"; // Handles "hours" scenario (also minutes and seconds) export const zonedAddDuration1 = ( isoDateStr: string, zoneIana: string, ...
🌐
npm
npmjs.com › package › date-fns
date-fns - npm
import { compareAsc, format } from "date-fns"; format(new Date(2014, 1, 11), "yyyy-MM-dd"); //=> '2014-02-11' const dates = [ new Date(1995, 6, 2), new Date(1987, 1, 11), new Date(1989, 6, 10), ]; dates.sort(compareAsc); //=> [ // Wed Feb 11 1987 00:00:00, // Mon Jul 10 1989 00:00:00, // Sun Jul 02 1995 00:00:00 // ]
      » npm install date-fns
    
Published   Sep 17, 2024
Version   4.1.0
🌐
DEV Community
dev.to › marinamosti › -formatting-and-modifying-javascript-dates-with-date-fns-3df2
Formatting and modifying JavaScript dates with date-fns - DEV Community
September 23, 2019 - There are currently two big players when it comes to JavaScript libraries for date management. MomentJS and Date-FNS. Both libraries get the job done, they allow you to grab a Date object and format, add time, subtract time, etc.
🌐
Youmightnotneed
youmightnotneed.com › date-fns
You Might Not Need date-fns
Set the minutes to the given date. // https://date-fns.org/v3.5.0/docs/setMinutes import { setMinutes } from 'date-fns' // Set 45 minutes to 1 September 2014 11:30:40: setMinutes(new Date(2014, 8, 1, 11, 30, 40), 45) // => Mon Sep 01 2014 11:45:40