473,543 Members | 2,130 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

adding 2 times together

Hey Gang, I'm trying to figure out the best way to add two times together of
the format hh:mm:ss any suggestions would be great thanks Todd
Jul 23 '05 #1
15 7889
Ivo
"Stormkid" <ba*****@golden gate.net> wrote in message
news:41******** *************@n ewsreader.golde ngate.net...
Hey Gang, I'm trying to figure out the best way to add two times together of the format hh:mm:ss any suggestions would be great thanks Todd


Convert all to seconds, add, then convert back. This way you can easily add
a third time later. For example:

var t1='12:34:56';
var t2='10:10:03';

t1=t1.split(/\D/);
t2=t2.split(/\D/);
var x1=parseInt(t1[0])*60*60 + parseInt(t1[1])*60 + parseInt(t1[2]);
var x2=parseInt(t2[0])*60*60 + parseInt(t2[1])*60 + parseInt(t2[2]);
var s=x1+x2;
var m=Math.floor(s/60); s=s%60;
var h=Math.floor(m/60); m=m%60;
var d=Math.floor(h/24); h=h%24;
alert(d+':'+h+' :'+m+':'+s);

You may wish to add leading zero's to numbers below 10 etc.
--Iv
Jul 23 '05 #2
Ivo wrote:
[snip]

Convert all to seconds, add, then convert back. This way you can easily add
a third time later. For example:

[snip]

Here is a modification of Ivo's example, I've created toSec(), toHr()
and toDay() functions. Of course there is no input validation and the
actual functions can probably be made more efficient.

You may still want to add leading zeros and include either toHr() or
toDay(), not both.

It is also more correct to use

this.form.eleme nts['time1'].value

rather than the shorter but probably just as reliable:

this.form.time1 .value
Cheers, Fred.

<script type="text/javascript">
function toSec(t) {
var b = t.split(/\D/);
return (+b[0])*60*60 + (+b[1])*60 + (+b[2]);
}

function toHr(s){
var m = Math.floor(s/60);
var h = Math.floor(m/60);
return h + ':' + m%60 + ':' + s%60;
}

function toDay(s){
var m = Math.floor(s/60);
var h = Math.floor(m/60);
var d = Math.floor(h/24);
return d + ':' + h%24 + ':' + m%60 + ':' + s%60;
}
</script>

<p>Enter times of format: hh:mm:ss</p>
<form name="fred" action="">
<input type="text" name="time1" cols="10">&nbsp ;&nbsp;
<input type="text" name="time2" cols="10"><br>
<input type="button" value="Add times" onclick="
alert('Hours: ' + toHr(toSec(this .form.time1.val ue)
+ toSec(this.form .time2.value))
+ '\nDays: ' + toDay(toSec(thi s.form.time1.va lue)
+ toSec(this.form .time2.value))) ;
">
</form>
Jul 23 '05 #3
Fred Oz wrote:

[snip]
You may still want to add leading zeros ...

[snip]
Here's an "add leading zeros" function that will add a
leading zero if the number passed has only one digit:

function addZero(x) {
if (String(x).leng th < 2) x = '0' + x;
return x;
}
Use it like this in toHr()

return addZero(h) + ':' + addZero(m%60) + ':'
+ addZero(s%60);
Rob
Jul 23 '05 #4
The result would be undefined
Why would you want to add - say 11:55pm to 7:36am ?
I could see adding 2 hours and 45 minutes to a time, or something like that.
Please clue us in on your purpose

"Stormkid" <ba*****@golden gate.net> wrote in message
news:41******** *************@n ewsreader.golde ngate.net...
Hey Gang, I'm trying to figure out the best way to add two times together of the format hh:mm:ss any suggestions would be great thanks Todd

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.770 / Virus Database: 517 - Release Date: 9/27/2004
Jul 23 '05 #5
JRS: In article <41************ *********@newsr eader.goldengat e.net>,
dated Mon, 27 Sep 2004 14:17:40, seen in news:comp.lang. javascript,
Stormkid <ba*****@golden gate.net> posted :
Hey Gang, I'm trying to figure out the best way to add two times together of
the format hh:mm:ss any suggestions would be great thanks Todd


It makes no sense to add times, but it is perfectly OK to add durations.

The following illustrates what may be the shortest codes, for totals
less than 24 hours :-

D0 = "1970/1/3 " ; G = " GMT"
T1 = "11:22:33"
T2 = "01:55:44"

T3 = (new Date(+new Date(D0+T1+G) + +new Date(D0+T2+G))) .toGMTString(). m
atch(/\d\d:\d\d:\d\d/)

T3 = (new Date(+new Date(D0+T1+G) + +new Date(D0+T2+G))) .toGMTString(). s
ubstr(16, 8)

The second makes more assumptions. Both are slightly tested.
The method of Iv (Ivo) fails if any field is 08 or 09 (FAQ 4.12). Using
parseInt() serves no purpose for hh & mm, and a unary + is enough for
ss.

Fred's looks OK apart from leading zeroes; I think that it has two
superfluous (+ ) .

Rob's usable leading zero function has the defects that it sometimes
returns a string & sometimes a number, and that if it returns a number
the number-to-string conversion will be repeated. Consider
if ((x=String(x)). length < 2) x = '0' + x;

<FAQENTRY> Optimal LZ function needed!

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #6
rh
Dr John Stockton wrote:
<...>
and that if it returns a number
the number-to-string conversion will be repeated. Consider
if ((x=String(x)). length < 2) x = '0' + x;

<FAQENTRY> Optimal LZ function needed!


Optimal is always desirable, but it seems that there is often no
single optimally efficient computation, and/or optimally expressed
computation, because of the variations in the ways in which JS engines
peform in different browsers. Whether, for example, a type conversion
is carried out more than once may be less important regarding
computational efficiency than the actual expression used to manifest
the result.

In this given case, differences in performance will likely occur based
on whether the input value is provided as a string or as an integer.
A couple of alternatives to your suggestion above, always returning a
string, are:

x = "" + (-(x > 9) && "") + +x;

and

x = x < 10 ? "0" + +x : "" +x;

with the former being somewhat oblique, but reasonably efficient (and
just slightly different in the treatment of extraneous leading zeros
in the input string), while the latter is expressed more clearly, and
is more efficient with string input. The latter, without saying it is
the best that can be done, should also provide better balance of
efficient computation across browsers and input type.

../rh
Jul 23 '05 #7
JRS: In article <29************ **************@ posting.google. com>,
dated Tue, 28 Sep 2004 19:24:33, seen in news:comp.lang. javascript, rh
<co********@yah oo.ca> posted :
Dr John Stockton wrote:
<...>
and that if it returns a number
the number-to-string conversion will be repeated. Consider
if ((x=String(x)). length < 2) x = '0' + x;

<FAQENTRY> Optimal LZ function needed!
Optimal is always desirable, but it seems that there is often no
single optimally efficient computation, and/or optimally expressed
computation, because of the variations in the ways in which JS engines
peform in different browsers. Whether, for example, a type conversion
is carried out more than once may be less important regarding
computationa l efficiency than the actual expression used to manifest
the result.

In this given case, differences in performance will likely occur based
on whether the input value is provided as a string or as an integer.


In the overwhelming majority of cases, the programmer will know whether
the input is a string or an integer.

The Leading Zero function is essentially a function for integer input.
If such string padding is wanted, it can either be done using a general
string padder, or an optimised string padder, or by tolerably
inefficient use of an integer function.

Rob's, omitting String( ) , is presumably optimum for strings.

One important question is whether it is *certain* that the number input
will be an integer in 0..99. If it is *certain* - which is the case for
getHours, etc. - then more methods become available, such as adding 100,
converting to string, and taking the last two characters (which is the
fastest way I know in MSIE4 VBscript). Otherwise, I would choose to
preserve the numerical value at the expense of format.
A couple of alternatives to your suggestion above, always returning a
string, are:

x = "" + (-(x > 9) && "") + +x;

and

x = x < 10 ? "0" + +x : "" +x;

with the former being somewhat oblique, but reasonably efficient (and
just slightly different in the treatment of extraneous leading zeros
in the input string), while the latter is expressed more clearly, and
is more efficient with string input. The latter, without saying it is
the best that can be done, should also provide better balance of
efficient computation across browsers and input type.


The second + seems unnecessary in the latter.

For non-negative integers,
'0'.substring(X >=10)+X // short but slow?
'0'.substr(X>=1 0)+X // shorter but slow?
I use
function LZ(x) { return (x<0||x>=10?"": "0") + x }
--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #8
rh
Dr John Stockton wrote:
<co********@yah oo.ca> posted :
Dr John Stockton wrote:
<...>
and that if it returns a number
the number-to-string conversion will be repeated. Consider
if ((x=String(x)). length < 2) x = '0' + x;

<FAQENTRY> Optimal LZ function needed!
Optimal is always desirable, but it seems that there is often no
single optimally efficient computation, and/or optimally expressed
computation, because of the variations in the ways in which JS engines
peform in different browsers. Whether, for example, a type conversion
is carried out more than once may be less important regarding
computationa l efficiency than the actual expression used to manifest
the result.

In this given case, differences in performance will likely occur based
on whether the input value is provided as a string or as an integer.


In the overwhelming majority of cases, the programmer will know whether
the input is a string or an integer.


Possibly. But perhaps in a typeless language, in the overwhelming
majority of cases, it shouldn't be necessary for the programmer to
differentiate between the two. If it is, then it seems most sensible
to present the utility a prototype of the core object (not that you've
suggested anything to the contrary).
The Leading Zero function is essentially a function for integer input.
If such string padding is wanted, it can either be done using a general
string padder, or an optimised string padder, or by tolerably
inefficient use of an integer function.

Rob's, omitting String( ) , is presumably optimum for strings.
Somewhat surprisingly, it appears not to be. And that's what I meant
when saying "optimal" is hard to achieve as it depends on which JS
engine is performing the computation. Outside IE, computation
efficiency of that expression in several of the more popular browsers
(even with String() omitted) ranges in my tests from slow to dismal.

The point is that it is non-trivial to assess computational efficiency
by simply looking at the operations in an expression.

One important question is whether it is *certain* that the number input
will be an integer in 0..99. If it is *certain* - which is the case for
getHours, etc. - then more methods become available, such as adding 100,
converting to string, and taking the last two characters (which is the
fastest way I know in MSIE4 VBscript). Otherwise, I would choose to
preserve the numerical value at the expense of format.
A couple of alternatives to your suggestion above, always returning a
string, are:

x = "" + (-(x > 9) && "") + +x;

and

x = x < 10 ? "0" + +x : "" +x;
<...>
The second + seems unnecessary in the latter.
It's there to allow for a string with extraneous leading zeros, e.g.,
input of "09", which would be returned as "009" otherwise.

For non-negative integers,
'0'.substring(X >=10)+X // short but slow?
'0'.substr(X>=1 0)+X // shorter but slow?
Also, perhaps:

["0",""][+(x>=10)]+x; // short but (surprisingly) slow
I use
function LZ(x) { return (x<0||x>=10?"": "0") + x }


Which is good, probably optimal -- to be improved only by making it a
prototype :).

../rh
Jul 23 '05 #9
rh wrote:
x = x < 10 ? "0" + +x : "" +x;

<...>

The second + seems unnecessary in the latter.


It's there to allow for a string with extraneous leading zeros, e.g.,
input of "09", which would be returned as "009" otherwise.
I use
function LZ(x) { return (x<0||x>=10?"": "0") + x }


Which is good, probably optimal -- to be improved only by making it a
prototype :).


But allows for a string with extraneous leading zeros:

function LZ(x) { return (x<0||x>=10?"": "0") + x }
alert(LZ('09')) ;

This could be corrected with:

function LZ(x) { return (x<0||x>=10?"": "0") + +x }
alert(LZ('09')) ;

Alternatively:

String.prototyp e.LZ = function() { return (+this).LZ(); }
Number.prototyp e.LZ = function() { return (this < 0 || this >= 10 ? "" : "0")
+ this; }
alert("09".LZ() ); alert((9).LZ()) ;

--
Grant Wagner <gw*****@agrico reunited.com>
comp.lang.javas cript FAQ - http://jibbering.com/faq

Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
2922
by: Sunny K | last post by:
Hi guys, I have a field in my DB called EventDate as a DateTime field, therefore it holds both the date and time together like this: '2004-10-14 08:42:57.000'. I need to add together all the times in this column for a particular date range (BETWEEN). Any suggestions will be great.
2
5573
by: Rob Kopp | last post by:
I have a query that I need a hand on. I am trying to add togther some fiends based on values of another. What I would like to add a billing total by saying more or less the following: SELECT labor_hours, labor_cost, expidite_fee, flat_rate, include_repair_cost, include_cal, include_flat_rate, include_parts, cur_bill, (labor_hours *...
1
1430
by: Diet Simon | last post by:
Can someone tell me about any software that adds up times? Example: I need to bill someone for work on separate days. 1 day I work 1hr 25 mins, the next 4 hours 17 mins, the next 25 mins and so on. I once knew of a stopwatch type thing for broadcasters that did that. wish i could find and buy it. I can't work Excel which has the facility.
0
1068
by: Drum2001 | last post by:
I am running a query to calculate overtime: SELECT .Employee, .TimeTypeIn, sectodur(IIf(Sum(DateDiff("s",,))-40*60*60>0,Sum(DateDiff("s",,))-40*60*60,0)) AS Overtime, DateAdd("d",-Weekday(),)+1 AS WeekOf FROM GROUP BY .Employee, .TimeTypeIn, DateAdd("d",-Weekday(),)+1 HAVING (((.TimeTypeIn)="Regular"));
2
4040
by: jho | last post by:
hello, I have a pricing sheet form and have the following fields in one row: SKU DESC UNIT PRICE QTY PRICE I want to select the sku in the form and have the corresponding desc and unit price fill in automatically and then manually input the qty
1
2945
by: Nigel Heald | last post by:
Hi Folks, We have a form that records flight times in hours and minutes, for example a 1 hour 15 minute flight is recorded as 1:15 Does anyone know how to get Access 2003 to calculate a total figure for a number of flight times recorded in a datasheet form? and is there a way to display flight times greater than 24 hours i.e 26:20 for...
6
6550
by: santiago | last post by:
I guess one cannot do this: arraytot = arraytot + arraydet; So, what's the trick to adding arrays like this? Thanks.
2
3443
Thekid
by: Thekid | last post by:
I know python has math functions like 5+6 and 5*6 and 5/6 etc...but I have something like this: x=575124357 and need to add them all together: 5+7+5+1+2+4+3+5+8=40
0
7397
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7726
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
5877
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5257
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4884
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3385
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1809
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
948
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
626
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.