public Blog<BenR>

Ben Reichelt's Blog

<December 2008>
SuMoTuWeThFrSa
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910


Navigation

Blogs

Subscriptions

Post Categories



Friday, January 07, 2005 - Posts

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;
}

posted Friday, January 07, 2005 3:35 PM by reic0113




Powered by Dot Net Junkies, by Telligent Systems