Mailing List Archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [tlug] [OT] Subtracting two times in JavaScript



On Sat, 20 Mar 2010 22:42:21 +0900, Dave M G <dave@example.com> wrote:

> diff = new Date(endTime.getTime() - currTime.getTime());

This is one area where you're going wrong.

If you look at the Date object, you'll see that you should supply the
date/time that the object is supposed to represent as an argument to the
constructor, not a time difference.

Simply subtract the results of the getTime() method of one object from that
of the other, and you'll get the number of milliseconds elapsed between the
two.

Something like this:

var elapsed = end.getTime() - currTime.getTime();
// Chop off the last 3 digits to discard the milliseconds and convert to
// an integer on the fly
var seconds = parseInt(elapsed.slice(0,-3),10);

Now download and use this javascript implementation of sprintf():

http://code.google.com/p/sprintf/

Finally, you can express "seconds" in hh:mm:ss format this way:

var hh,mm,ss,hms;
ss = seconds % 60;
seconds = ( seconds - ss ) / 60;
mm = seconds % 60;
seconds = ( seconds - mm ) / 60;
hms = sprintf("%02d:%02d:%02d",hh,mm,ss);

-- 
G. Stewart - gstewart@example.com

A clear conscience is usually the sign of a bad memory.

Attachment: pgp5XlqTtZkwO.pgp
Description: PGP signature


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links