Date.AddMinutes()

I really wanted an AddMinutes() method to use in javascript like C# has. So I set out to write one myself.

I soon realized how complicated it could get, for instance, the minutes could move the date to the next day, month, or year. I started writing down all the conditions to check, to make sure that I could handle all situations. Since javascript uses the setMinutes(), setHours(), setMonth(), etc.. style of altering a date, I was going to parse the minutes into the number of months, days, hours, and minutes that were represented by the minutes. So 10080 minutes would equal 7 days. After I did that I could add all the appropriate fields and then get my new date.
Then I realized a MUCH easier way to get it done. There is a Date method called getTime() that returns the number of milliseconds since 1/1/1970. There is also a Date constructor that takes in an integer, which also represents the number of milliseconds since 1/1/1970. So all I had to do was use the getTime() method, convert the minutes that I want to add into milliseconds, add the milliseconds and the create a new date instance with this new value. Much, much easier and I don’t have the headache of managing all those situations mentioned above, whew!! Here’s the code I used:
function addMinutes(dateTimeObj, iMinutes) {

var length = iMinutes * 60 * 1000;

var iseconds = dateTimeObj.getTime();

iseconds += length;

var dt = new Date(iseconds);

return dt;

}

2 Comments

  1. Anonymous said,

    Wrote on January 8, 2005 @ 2:21 am

    Too much trouble. The next script snippet will show 18:06 as time.

    alert(new Date(2005,1,8,17,66,00));

    Note that I specified 66 as the minute parameter. The Date() function is able to handle overflows perfectly.

    Adding 5 minutes:

    <script>

    var now = new Date();

    alert(new Date(now.getYear(),now.getMonth(),now.getDate(),now.getHours(),now.getMinutes()+5,now.getSeconds()));

    </script>

  2. Anonymous said,

    Wrote on January 8, 2005 @ 2:46 am

    ahh, very nice, that’s even easier still

Comment RSS