OpenNTF.org - Javascript version of @Adjust
My Links (Not logged in)
Code Bin Search
 
Hosted by Prominic.NET
Rate This Code
5 - brilliant stuff
4 - very nice
3 - average
2 - needs work
1 - bad
   OpenNTF Code Bin
About This Code
Brief Description:
Javascript version of @Adjust 
Rating:
Rating: 5 , Number of votes: 2 
Contributor:
Andrew Tetlaw 
Category:
Javascript 
Type:
Date/Time functions 
Last Modified:
23 Feb 2007 
OpenNTF Disclaimer

All of the program code and information presented in the OpenNTF.org Code Bin are provided "as-is", and should be used at your own risk. OpenNTF.org make no express or implied warranty about anything in the Code Bin, and OpenNTF.org will not be responsible or liable for any damage caused by the use or misuse of anything from this site. OpenNTF.org makes no guarantees about anything. Please thoroughly test all of the knowledge and code you find here before you attempt to use them in your production environment.

Code / Description
I liked the simplicity of being able to adjust a date using @Adjust in Notes and wanted the same simplicity in Javascript. So here it is:


Date.prototype.adjust = function(yr,mn,dy,hr,mi,se) {
var m,t;
this.setYear(this.getFullYear() + yr);
m = this.getMonth() + mn;
if(m != 0) this.setYear(this.getFullYear() + Math.floor(m/12));
if(m < 0) {
this.setMonth(12 + (m%12));
} else if(m > 0) {
this.setMonth(m%12);
}
t = this.getTime();
t += (dy * 86400000);
t += (hr * 3600000);
t += (mi * 60000);
t += (se * 1000);
this.setTime(t);
}

Usage / Example
var d = new Date();
d.adjust(years, months, days, hours, minutes, seconds);

Each argument is required, you pass a positive or negative number to adjust the date by that value or pass 0 for no change.

You can supply positive or negative numbers just like in @Adjust. It copes with year roll over if you, for example, add 15 months or -15 months to the date or even if it's December and you increment the month by 2.
 Comments
Posted by mdm adph on 12/20/2006 12:10:25 PMgood code!
very good code -- i'm making this part of my standard utility library right away.
also, thanks for reminding me of the fact that javascript is able to declare multiple variables using just one "var" -- I have no idea why I had forgotten that.
Posted by Andrew Tetlaw on 02/23/2007 06:33:22 PMFixed a bug
Oops, for got JS months were 0 - 11 ! Above code is fixed.
Posted by Rajni Huria on 09/16/2009 05:58:02 PMIts not working for me
when i try to use this code..it returns me "Undefined" value..
Any idea??
-thanks
Posted by Joe Ellis on 08/31/2010 11:54:15 AMfix for "Undefined"
need to add 'return this' as the last line in the function, then it works great. Probably too late to help Rajni, but maybe this will be of use to whoever finds this next.
 Add your comment!