PDA

View Full Version : Date().getElapsed() (Human Readable Version!)



foxwhisper
26 Jan 2009, 10:58 AM
So like.. I spent ages searching around on the intarwebz for a piece of code which would convert milliseconds to a human readable string (0 days, 0 hrs, 0 mins, 0 secs) etc, but could I find one? No lol. So I wrote one instead :D

To use the below, use it exactly as you would with getElapsed. The only difference being, it will return a human readable string, rather than the number of milliseconds.

Here is an example of using it with MySQL Dates


Date1='2009-01-01 01:01:01';
Date2='2009-01-02 01:01:02';

return new Date.parseDate(Date1, "Y-m-d H:i:s").getElapsedHuman(new Date.parseDate(Date2,"Y-m-d H:i:s"));


Maybe it should be extended to say 'minus' days etc, if the second date is higher than the first date?? I dunno.. For now, here it is :D Enjoy!



Ext.override(Date, {
getElapsedHuman : function(otherDate) {
try {
ms = this.getElapsed(otherDate)/1000;
} catch (Exception) {
throw "Invalid Comparison Date: "+Exception
}

// Instantiate counters
days=0;
hrs=0;
mins=0;
secs=0;
out=[];

// Check how many days
while (ms>=86400) {
days++;
ms-=86400;
}

// Check how many hours
while (ms>=3600) {
hrs++;
ms-=3600;
}

// Check how many minutes
while (ms>=60) {
mins++;
ms-=60;
}

// Check how many seconds
while (ms>0) {
secs++;
ms-=1;
}

// Append each one into the out buffer
if (days) { out.push(days+" days") }
if (hrs) { out.push(hrs+" hrs") }
if (mins) { out.push(mins+" mins") }
if (secs) { out.push(secs+" secs") }

// Then join each one together, and boom! :)
return out.join(", ");
}
});

mystix
26 Jan 2009, 12:15 PM
i think you should consider switching to the modulo operator as opposed to performing your calculations in while() loops...

foxwhisper
26 Jan 2009, 12:22 PM
Really sorry for the 'noobish' question but.. Do you have an example of a 'modulo operation' in JavaScript?? I feel so stupid asking, but it's not a term I've come across before in my programming years :o

Cal <3

wemerson.januario
26 Jan 2009, 12:41 PM
Can you post a pratic example of the use? I fell stupid asking too! heheh Thanks

Animal
27 Jan 2009, 5:50 AM
// Check how many days
var r = ms % 86400; // modulo operator. Gets remainder of integer division ms / 86400
days = (ms - r) / 86400;
ms = r;

Animal
27 Jan 2009, 5:51 AM
PS: declare your variables with var otherwise they will be global.

temporary
28 Jan 2009, 3:57 PM
Nice idea.

It would be cool if the word-parts could be translated... We are using the german locales. Don't know, maybe these words are already present in the locales...