PDA

View Full Version : tween dates



Cremator
01-24-2012, 04:42 PM
This is a simple function that you pass a couple of RFC strings containg dates or date and time information and the function returns the number of milliseconds between those dates


function tween(rfcDateBegin,rfcDateEnd){
rfcDateBegin = rfcDateBegin || false;
rfcDateEnd = rfcDateEnd || false;
if( rfcDateBegin && rfcDateEnd ) return Math.floor( new Date(rfcDateEnd).getTime() - new Date(rfcDateBegin).getTime() );
return null;
}

Example:

// return the number of milliseconds in the year
milliseconds = tween("1 Jan 2012","31 Dec 2012");

Returns the number of milliseconds between the dates supplied, returns a negative value if the future date is passed first, allows you to determine from an input if a date is in the past or not.

Philip M
01-25-2012, 07:59 AM
Returns the number of milliseconds between the dates supplied, returns a negative value if the future date is passed first, allows you to determine from an input if a date is in the past or not.

To be strictly accurate, returns a negative number if the DateEnd is before the DateBegin, but of course one or both both dates could be in the past.

Could extend to show the number of days:-


milliseconds = tween("1 January 2012","31 Dec 2012");
alert (milliseconds);
days = milliseconds/86400/1000;
days = days+1; // inclusive number of days in period
alert (days);

Cremator
01-26-2012, 03:36 PM
Yep, that is true and I have a modified version but stripped the function down to an elementary function that returns milliseconds which can be easily manipulated.

Eg.
function tween_days(rfcDateBegin,rfcDateEnd){
rfcDateBegin = rfcDateBegin || false;
rfcDateEnd = rfcDateEnd || false;
if( rfcDateBegin && rfcDateEnd ) return tween(rfcDateBegin,rfcDateEnd)/86400000;
return null;
}

Its a nice little function that at first glance appears not to do much but offers plenty of scope in other functions or simply extending its use.