MySQL TO_SECONDS() Function
The MySQL TO_SECONDS() function returns the date or datetime value converted to seconds. This function returns the number of seconds between a given date/datetime value and year 0. It returns NULL if datetime is 0.
This function is to be used only with dates within the Gregorian calendar.
Syntax
TO_SECONDS(datetime)
Parameters
datetime |
Required. Specify a date or datetime value to convert to seconds. |
Return Value
Returns the converted seconds.
Example 1:
The example below shows the usage of TO_SECONDS() function.
mysql> SELECT TO_SECONDS('2018-08-18'); Result: 63701769600 mysql> SELECT TO_SECONDS('2018-08-18 10:38:42'); Result: 63701807922 mysql> SELECT TO_SECONDS('2018-08-18 10:38:42.000004'); Result: 63701807922 mysql> SELECT TO_SECONDS(20180818); Result: 63701769600 mysql> SELECT TO_SECONDS('0000-01-01'); Result: 86400 mysql> SELECT TO_SECONDS('0000-00-00'); Result: NULL
Example 2:
Consider a database table called Employee with the following records:
EmpID | Name | City | Age | Date_of_Joining |
---|---|---|---|---|
1 | John | London | 25 | 2018-05-25 |
2 | Marry | New York | 24 | 2018-10-15 |
3 | Jo | Paris | 27 | 2019-06-09 |
4 | Kim | Amsterdam | 30 | 2019-09-21 |
5 | Ramesh | New Delhi | 28 | 2019-10-25 |
6 | Suresh | Mumbai | 28 | 2021-12-26 |
The statement given below can be used to convert the records of column Date_of_Joining into seconds:
SELECT *, TO_SECONDS(Date_of_Joining) AS TO_SECONDS_Value FROM Employee;
This will produce the result as shown below:
EmpID | Name | City | Age | Date_of_Joining | TO_SECONDS_Value |
---|---|---|---|---|---|
1 | John | London | 25 | 2018-05-25 | 63694425600 |
2 | Marry | New York | 24 | 2018-10-15 | 63706780800 |
3 | Jo | Paris | 27 | 2019-06-09 | 63727257600 |
4 | Kim | Amsterdam | 30 | 2019-09-21 | 63736243200 |
5 | Ramesh | New Delhi | 28 | 2019-10-25 | 63739180800 |
6 | Suresh | Mumbai | 28 | 2021-12-26 | 63807696000 |
❮ MySQL Functions