I have the old database in which time was stored as string with AM/PM. One day I required to do some time calculation on that field. I have googled out for convert time string into time with AM/PM in MySQL and found some solution.
Here is the Database tables:
1 2 3 4 5 6 | ID empId inTime outTime 1 12 10:10:00 AM 04:00:00 PM 2 13 10:10:00 AM 05:00:00 PM 3 14 10:10:00 AM 03:00:00 PM 4 15 10:10:00 AM 05:00:00 PM 5 11 10:10:00 AM 06:00:00 PM |
Now by these records, I want to get the time availability of the employee by calculating time difference between inTime and outTime fields.
To do this in MySQL we use the STR_TO_DATE() function, which has two parameters. The first parameter is the time to be parsed and the second is the format of that time. Here is a simple example that converts one date format to a MySQL formatted date string.
Example
1 | SELECT STR_TO_DATE('11:15 PM', '%h:%i %p') ; |
So for calculating time difference in above given records, use following steps:
1. convert time string fields into date/time format
2. By using timediff function, get the difference between these 2 fields
1 | SELECT empId, TIMEDIFF(STR_TO_DATE(outTime, '%h:%i %p'),STR_TO_DATE(inTime, '%h:%i %p')) as availTime from tablename ; |
This query will result as follows
1 2 3 4 5 6 | empId availTime 12 05:50:00 13 06:50:00 14 04:50:00 15 06:50:00 11 07:50:00 |