Calculating Intervals Between Times

5.15.1 Problem

You want to know the amount of time elapsed between two times.

5.15.2 Solution

Convert the times to seconds with TIME_TO_SEC( ) and take the difference. For a difference represented as a time, convert the result back the other way using SEC_TO_TIME( ).

5.15.3 Discussion

Calculating intervals between times is similar to adding times together, except that you compute a difference rather than a sum. For example, to calculate intervals in seconds between pairs of t1 and t2 values, convert the values in the time_val table to seconds using TIME_TO_SEC( ), then take the difference. To express the resulting difference as a TIME value, pass it to SEC_TO_TIME( ). The following query shows intervals both ways:

mysql> SELECT t1, t2,
 -> TIME_TO_SEC(t2) - TIME_TO_SEC(t1) AS 'interval in seconds',
 -> SEC_TO_TIME(TIME_TO_SEC(t2) - TIME_TO_SEC(t1)) AS 'interval as TIME'
 -> FROM time_val;
+----------+----------+---------------------+------------------+
| t1 | t2 | interval in seconds | interval as TIME |
+----------+----------+---------------------+------------------+
| 15:00:00 | 15:00:00 | 0 | 00:00:00 |
| 05:01:30 | 02:30:20 | -9070 | -02:31:10 |
| 12:30:20 | 17:30:45 | 18025 | 05:00:25 |
+----------+----------+---------------------+------------------+

Note that intervals may be negative, as is the case when t1 occurs later than t2.

Using the mysql Client Program

Writing MySQL-Based Programs

Record Selection Techniques

Working with Strings

Working with Dates and Times

Sorting Query Results

Generating Summaries

Modifying Tables with ALTER TABLE

Obtaining and Using Metadata

Importing and Exporting Data

Generating and Using Sequences

Using Multiple Tables

Statistical Techniques

Handling Duplicates

Performing Transactions

Introduction to MySQL on the Web

Incorporating Query Resultsinto Web Pages

Processing Web Input with MySQL

Using MySQL-Based Web Session Management

Appendix A. Obtaining MySQL Software

Appendix B. JSP and Tomcat Primer

Appendix C. References



MySQL Cookbook
MySQL Cookbook
ISBN: 059652708X
EAN: 2147483647
Year: 2005
Pages: 412
Authors: Paul DuBois

Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net