Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Easy date subtraction not working

Status
Not open for further replies.

cryoburned

Programmer
May 23, 2006
14
US
I'm trying to get this script to work:


var year = time.getYear();
var months = time.getMonth();
var days = time.getDate();
var prestamp = Math.ceil((year*10000)+(months*1000)+days);
var posteddate = 20061121;
document.write(Math.ceil(prestamp-posteddate));

Basically it should put November 23, 2006 - November 21, 2006 = 2 by using date stamps (20061123-20061121=2) But in IE and FF nothing shows up.. its just blank.. Suggestions?
 
I see 2 suggestions:

(a) add 1 to the getMonth() value - it is 0 to 11 not 1 to 12 as you want.

(b) multiply months by 100 not 1000

That should provide the right result.
 
I would also use getFullYear() just to make sure you're working with a 4-digit year.

And when I format a date like that I use this method:
Code:
var prestamp = parseInt(year + '' + months + '' + days, 10);

Your algorithm will only work within a single month, and won't give accurate results if the start date is in one month and the end date is in another.

Lee
 
Awesome comment speed.. thanks.. so.. anyone know how i can subtract dates across months (and maybe years?)
 
Look at the getTime() method of the Date() object.

Microsoft JScript Help said:
The getTime method returns an integer value representing the number of milliseconds between midnight, January 1, 1970 and the time stored in the Date object. The range of dates is approximately 285,616 years from either side of midnight, January 1, 1970. Negative numbers indicate dates prior to 1970.

By using this method with each date, you can subtract one from the other and convert the result to seconds, minutes, hours, days, weeks, whatever you want.

Lee
 
Awesome and thank you. Do you have the link to microsoft help so i can explore this?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top