Javascript Date difference as milliseconds, minutes, hours, days, weeks, months, or years

Posted by stephen on November 13th, 2009

I needed to figure out the difference between two dates in Javascript, so I wrote up this function. It takes into account the days in each month as well as leap years. It will calculate years, months, weeks, days, hours, minutes, seconds, and milliseconds, or any combination of those. For example, if you want months and hours, this’ll do ya.

Let me know if anyone finds a discrepancy in the calculations.

sample.html
timeSpan.js

View source of the sample page above for usage. Samples include a date comparison and a date countown.

IE6 and form.submit() bug workaround

Posted by stephen on November 3rd, 2009

IE6………one of life’s great mysteries. I think we may need some federally enforced browser standards more than a new health care system, but that’s just me.

In IE6, programatically triggering the submit() method of a form element doesn’t *always* seem to work. There’s no logical reason - it just doesn’t. I’ve run into this problem twice now. The first time, I just ended up building a query string out of the form variables and using window.location to send them to the action page. That was with a static form. I just hit this wall again with a form I’m building dynamically.

For *whatever* reason, delaying the submit action by 100ms works like a charm. I wish I could tell you more, but as with all IE6 bug fixes, when they work, I try not to ask questions.

Here’s what I ended up doing:

I tried building the form through the browser’s native methods, using document.createElement() and element.appendChild(), which didn’t make a difference, so I reverted back to created the form with jQuery. So, here’s what I ended up doing….

/* ....build form elements using jQuery... */
$j("body").append(form);

setTimeout(function(){
	form.submit();
}, 100);

Hope this saves someone some time! If you’re dealing with a form that is not being built dynamically, I have an inkling that this may not work. Still, delaying the event another way might. Try this, and if it works for you, let me know!

<a href="javascript:;" onclick="setTimeout(function(){ form.submit() }, 100)">Submit</a>

That’s the onclick event of an anchor tag, but the same would apply for the onclick of any element.


Copyright © 2007 Stephen Rushing. All rights reserved.