- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the difference between two timestamps in days with MySQL
Use DATEDIFF() function from MySQL to get the difference between two timestamps in days.
The syntax is as follows −
select datediff(yourColumnName1,yourColumnName2) as anyVariableName from yourTableName;
To understand the above syntax, let us create a table. The following is the query to create a table −
mysql> create table DifferenceTimestamp −> ( −> IssueTime timestamp, −> DueTime timestamp −> ); Query OK, 0 rows affected (0.66 sec)
Insert some records in the table with the help of insert command. We are setting dates here. The query is as follows −
mysql> insert into DifferenceTimestamp values(now(),date_add(now(),interval -30 Day)); Query OK, 1 row affected (0.12 sec) mysql> insert into DifferenceTimestamp values(now(),date_add(now(),interval -24 Day)); Query OK, 1 row affected (0.16 sec) mysql> insert into DifferenceTimestamp values(now(),date_add(now(),interval -5 Day)); Query OK, 1 row affected (0.14 sec)
Display all records from the table with the help of select statement. The query is as follows −
mysql> select *from DifferenceTimestamp;
The following is the output −
+---------------------+---------------------+ | IssueTime | DueTime | +---------------------+---------------------+ | 2018-12-07 17:48:28 | 2018-11-07 17:48:28 | | 2018-12-07 17:48:40 | 2018-11-13 17:48:40 | | 2018-12-07 17:48:46 | 2018-12-02 17:48:46 | +---------------------+---------------------+ 3 rows in set (0.00 sec)
Here is the query to get difference between two timestamps in days. The query is as follows −
mysql> SELECT DATEDIFF(IssueTime, DueTime) AS DifferenceInTimestampDays from DifferenceTimestamp;
The following is the output −
+---------------------------+ | DifferenceInTimestampDays | +---------------------------+ | 30 | | 24 | | 5 | +---------------------------+ 3 rows in set (0.00 sec)
Advertisements