Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calculate time difference 2

Status
Not open for further replies.

mstrcmtr

Programmer
Nov 14, 2007
103
PK
How calculate time between 2 given times in Hour minute seconds

e.g.

a = time()

b = time()

? b - a
 
Don't use TIME(). Use DATETIME().

a = DATETIME() gives the current date and time, to the nearest second, as a variable of Datetime type.

b = DATETIME(2018, 6, 28, 8, 15) gives a specific time and date, of Datetime type.

Subtracting one datetime from another gives the difference in seconds:

Secs = b - a

To convert to hours minutes and seconds, divide by 3600 (this gives you the number of hours), then divide the remainder by 60 (gives minutes), and the final remainder is the number of seconds.

Mike



__________________________________
Mike Lewis (Edinburgh, Scotland)

Visual FoxPro articles, tips and downloads
 
Just expand on that:

If diff is the difference (in seconds) between two datetimes, then:

Code:
hours = INT(diff / 3600)

minutes = INT((diff - (hours * 3600)) / 60)

seconds = diff - (hours * 3600) - (mins * 60)

By the way, it is advisable not to use single letters between a and j as variable names. The reason is that they might clash with the built-in single-letter table aliases. In practice, it will very rarely cause a problem, but most developers try to avoid it.

Mike



__________________________________
Mike Lewis (Edinburgh, Scotland)

Visual FoxPro articles, tips and downloads
 
And besides computing the elements of the time difference, an easy way to get from Seconds to HH:MM:SS is, of course, adding these seconds to a default date, eg:

Code:
dt1 = DATETIME(2018, 6, 28, 8, 15)
dt2 =  DATETIME(2018, 6, 28, 9, 35)
diffseconds = dt2-dt1
difft = DateTime(200,1,1,0,0,0)+diffseconds

? "The difference between", dt1, " and", dt2, " is", TToC(difft,2)

Because you can not only get the diff in seconds, you can also add seconds to a DateTime to get another one. And if you do so for a DateTime at midnight, the time portion is exactly what the seconds turn to in hours, minutes and seconds, especially in SET HOURS TO 24 mod without AM/PM display this works for essential differences below a day. Enough for example for appointment durations, working time logging etc.

In the end, store DateTimes of the points in time involved for your case, and you'll always be able to compute differences and display them in a human-readable format.

Bye, Olaf.

Olaf Doschke Software Engineering
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top