13

I am getting the current date as below:

var now = new Date();

I want to add 5 minutes to the existing time. The time is in 12 hour format. If the time is 3:46 AM, then I want to get 3:51 AM.

function DateFormat(date) {
        var days = date.getDate();
        var year = date.getFullYear();
        var month = (date.getMonth() + 1);
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var ampm = hours >= 12 ? 'PM' : 'AM';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0' + minutes : minutes;
        var strTime = days + '/' + month + '/' + year + '/ ' + hours + ':' + minutes + ' ' + ampm;
     //   var strTime = hours + ':' + minutes + ' ' + ampm;
        return strTime;
    }

    function OnlyTime(date) {

            var days = date.getDate();
            var year = date.getFullYear();
            var month = (date.getMonth() + 1);
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var ampm = hours >= 12 ? 'PM' : 'AM';
            hours = hours % 12;
            hours = hours ? hours : 12; // the hour '0' should be '12'
            minutes = minutes < 10 ? '0' + minutes : minutes;
           // var strTime = days + '/' + month + '/' + year + '/ ' + hours + ':' + minutes + ' ' + ampm;
              var strTime = hours + ':' + minutes + ' ' + ampm;
            return strTime;

    }

    function convertTime(time)
    {

        var hours = Number(time.match(/^(\d+)/)[1]);
        var minutes = Number(time.match(/:(\d+)/)[1]);
        var AMPM = time.match(/\s(.*)$/)[1];
        if (AMPM == "PM" && hours < 12) hours = hours + 12;
        if (AMPM == "AM" && hours == 12) hours = hours - 12;
        var sHours = hours.toString();
        var sMinutes = minutes.toString();
        if (hours < 10) sHours = "0" + sHours;
        if (minutes < 10) sMinutes = "0" + sMinutes;
        alert(sHours + ":" + sMinutes);
    }

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

function convertTime(time)
    {

        var hours = Number(time.match(/^(\d+)/)[1]);
        var minutes = Number(time.match(/:(\d+)/)[1]);
        var AMPM = time.match(/\s(.*)$/)[1];
        if (AMPM == "PM" && hours < 12) hours = hours + 12;
        if (AMPM == "AM" && hours == 12) hours = hours - 12;
        var sHours = hours.toString();
        var sMinutes = minutes.toString();
        if (hours < 10) sHours = "0" + sHours;
        if (minutes < 10) sMinutes = "0" + sMinutes;
        alert(sHours + ":" + sMinutes);
    }

// calling way
  var now = new Date();
                now = DateFormat(now);
                var next = addMinutes(now, 5);

                next = OnlyTime(next);

                var nowtime = convertTime(next);

How to add 5 minutes to the "now" variable? Thanks

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
venkat14
  • 583
  • 3
  • 12
  • 34
  • 8
    Possible duplicate of [How to add 30 minutes to a JavaScript Date object?](http://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object) – Philipp Feb 09 '17 at 08:49
  • 2
    uhm ... `now.setMinutes( now.getMinutes() + 5)` ? Don't be lazy. – KarelG Feb 09 '17 at 08:49
  • 2
    Use MomentJS instead. Despite seeming simple, time is just too easy to get wrong. – Peter G Feb 09 '17 at 08:50
  • Possible duplicate of [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – ric Jan 25 '18 at 10:16

8 Answers8

26

You should use getTime() method.

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

function AddMinutesToDate(date, minutes) {
     return new Date(date.getTime() + minutes*60000);
}
function DateFormat(date){
  var days = date.getDate();
  var year = date.getFullYear();
  var month = (date.getMonth()+1);
  var hours = date.getHours();
  var minutes = date.getMinutes();
  minutes = minutes < 10 ? '0' + minutes : minutes;
  var strTime = days + '/' + month + '/' + year + '/ '+hours + ':' + minutes;
  return strTime;
}
var now = new Date();
console.log(DateFormat(now));
var next = AddMinutesToDate(now,5);
console.log(DateFormat(next));
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
  • Hi @Alexandru-lonut Mihai. Is it possible to return only the time in 12 hour format in the above example – venkat14 Feb 09 '17 at 08:56
  • 1
    TypeError: Object doesn't support property or method 'getTime'. when the line hits now = DateFormat(now) , i get the value as "9/2/2017/ 4:44 AM" . This value is passed to var next = addMinutes(now, 5); In my earlier posts, I had mentioned 12 hour format by mistake, I am looking at getting 24 hour format, which I am trying to do in ConvertTime method – venkat14 Feb 09 '17 at 09:47
  • You are using IE ? – Mihai Alexandru-Ionut Feb 09 '17 at 09:52
  • Yes, I am using IE 11 – venkat14 Feb 09 '17 at 10:32
  • In Firestore Cloud Function using TypeScript, I'm getting error: `TypeError: date.getTime is not a function` – Mike Taverne May 26 '20 at 03:28
12

//Date objects really covers milliseconds since 1970, with a lot of methods
//The most direct way to add 5 minutes to a Date object on creation is to add (minutes_you_want * 60 seconds * 1000 milliseconds)
var now = new Date(Date.now() + (5 * 60 * 1000));
console.log(now, new Date());
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
10

get minutes and add 5 to it and set minutes

var s = new Date();
console.log(s)
s.setMinutes(s.getMinutes()+5);

console.log(s)
Vinod Louis
  • 4,812
  • 1
  • 25
  • 46
2

Quite easy with JS, but to add a slight bit of variety to the answers, here's a way to do it with moment.js, which is a popular library for handling dates/times:

https://jsfiddle.net/ovqqsdh1/

var now = moment();
var future = now.add(5, 'minutes');
console.log(future.format("YYYY-MM-DD hh:mm"))
OliverRadini
  • 6,238
  • 1
  • 21
  • 46
  • This answer is wrong because you're recommending to add an entire library to do that. The good way to do this is using native JS: `const date = new Date(); date.setMinutes(date.getMinutes() + 5);` – Jonathan Brizio Apr 22 '20 at 19:44
  • 2
    @JonathanBrizio That doesn't make it wrong, though, I don't think? In the answer I said `"to add a slight bit of variety to the answers, here's a way to do it with moment.js, which is a popular library"`; there are plenty of other answers which do not use libraries, and that's great; the question doesn't specify whether or not to use a library, so this is just one amongst many options. I don't claim that this is the _best_ way to solve a problem, just one option. – OliverRadini Apr 24 '20 at 16:10
  • It could be easy to do with this library, but you're adding more dependencies without sense. Anytime mention how to solve this with an external library. – Jonathan Brizio Apr 25 '20 at 16:03
  • 1
    @JonathanBrizio I think the conversation is closed - yes I'm adding a dependency, I don't suggest that's worth doing, but present it as an option - it's up to the OP, and any subsequent readers, to judge which of the options works best for them. This is over 3 years old and I don't think there's anything to be gained by discussing it further – OliverRadini Apr 26 '20 at 15:05
1

Try this:

var newDateObj = new Date();
newDateObj.setTime(oldDateObj.getTime() + (5 * 60 * 1000));
arghtype
  • 4,376
  • 11
  • 45
  • 60
Hajji Tarik
  • 1,072
  • 7
  • 23
0

I'll give a very short answer on how to add any string of the form ny:nw:nd:nh:nm:ns where n is a number to the Date object:

/**
 * Adds any date string to a Date object.
 * The date string can be in any format like 'ny:nw:nd:nh:nm:ns' where 'n' are
 * numbers and 'y' is for 'year', etc. or, you can have 'Y' or 'Year' or 
 * 'YEar' etc.
 * The string's delimiter can be anything you like.
 * 
 * @param Date date The Date object
 * @param string t The date string to add
 * @param string delim The delimiter used inside the date string
 */
function addDate (date, t, delim) {
   var delim = (delim)? delim : ':',
       x = 0,
       z = 0,
       arr = t.split(delim);

   for(var i = 0; i < arr.length; i++) {
      z = parseInt(arr[i], 10);
      if (z != NaN) {
         var y = /^\d+?y/i.test(arr[i])? 31556926: 0; //years
         var w = /^\d+?w/i.test(arr[i])? 604800: 0;   //weeks
         var d = /^\d+?d/i.test(arr[i])? 86400: 0;    //days
         var h = /^\d+?h/i.test(arr[i])? 3600: 0;     //hours
         var m = /^\d+?m/i.test(arr[i])? 60: 0;       //minutes
         var s = /^\d+?s/i.test(arr[i])? 1: 0;        //seconds
         x += z * (y + w + d + h + m + s);
      }
   }
   date.setSeconds(date.getSeconds() + x);
}

Test it:

var x = new Date();
console.log(x);    //before
console.log('adds 1h:6m:20s');
addDate(x, '1h:6m:20s');
console.log(x);   //after
console.log('adds 13m/30s');
addDate(x, '13m/30s', '/');
console.log(x);   //after

Have fun!

centurian
  • 1,168
  • 13
  • 25
0

This function will accept ISO format and also receives minutes as parameter.

function addSomeMinutesToTime(startTime: string | Date, minutestoAdd: number): string {
  const dateObj = new Date(startTime);
  const newDateInNumber = dateObj.setMinutes(dateObj.getMinutes() + minutestoAdd);
  const processedTime = new Date(newDateInNumber).toISOString();
  console.log(processedTime)
  return processedTime;
}
addSomeMinutesToTime(("2019-08-06T10:28:10.687Z"), 5)
Kushal Atreya
  • 183
  • 2
  • 7
0

Add minutes into js time by prototype

Date.prototype.AddMinutes = function ( minutes ) {
    minutes = minutes ? minutes : 0;
    this.setMinutes( this.getMinutes() + minutes );
    return this;
}

let now = new Date( );
console.log(now);

now.AddMinutes( 5 );
console.log(now);
M. Hamza Rajput
  • 7,810
  • 2
  • 41
  • 36