MySQL - TO_SECONDS() Function



The MYSQL TO_SECONDS() function accepts a date or datetime value as an argument and returns a numerical value representing the number of seconds since the year 0.

If the date passed as an argument to this function is 0 (or '0000-00-00'), the return value will be NULL.

Syntax

Following is the syntax of MySQL TO_SECONDS() function −

TO_SECONDS(date);

Parameters

This method accepts a valid date and time expression or column as a parameter.

Return value

This function in MySQL converts a given date and time expression to the number of seconds since the year 0 (year 1 BC).

Example

In the following example, we are using the MySQL TO_SECONDS() function to calculate the number of seconds for the specified date value since the year 0 −

SELECT TO_SECONDS('2023-11-20') As Result;

Output

This will produce the following result −

Result
63867657600

Example

Here, we are passing datetime value as an argument to this function −

SELECT TO_SECONDS('2023-11-21 12:35:58') As Result;

Output

Following is the output −

Result
63867789358

Example

The below query calculates the total number of seconds from the year 0 to the current date −

SELECT TO_SECONDS(CURDATE()) As Result;

Output

Following is the output −

Result
63867744000

Example

In the following example, let us create a table named ORDERS using CREATE TABLE statement −

CREATE TABLE ORDERS (
   OID INT NOT NULL,
   DATE VARCHAR (20) NOT NULL,
   CUSTOMER_ID INT NOT NULL,
   AMOUNT DECIMAL (18, 2)
);

Now, insert the following records into the ORDERS table using the INSERT statement −

INSERT INTO ORDERS VALUES 
(102, '2009-10-08 00:00:00', 3, 3000.00),
(100, '2009-10-08 00:00:00', 3, 1500.00),
(101, '2009-11-20 00:00:00', 2, 1560.00),
(103, '2008-05-20 00:00:00', 4, 2060.00);

Execute the below query to fetch all the inserted records in the above-created table −

Select * From ORDERS;

Following is the ORDERS table −

OID DATE CUSTOMER_ID AMOUNT
102 2009-10-08 00:00:00 3 3000.00
100 2009-10-08 00:00:00 3 1500.00
101 2009-11-20 00:00:00 2 1560.00
103 2008-05-20 00:00:00 4 2060.00

Now, we use the MySQL TO_SECONDS() function to calculates the number of seconds since the year "0" for each value in the "DATE" column −

Select OID, DATE, TO_SECONDS(DATE) As Result From ORDERS;

Output

The output is displayed as follows −

OID DATE Result
102 2009-10-08 00:00:00 63422179200
100 2009-10-08 00:00:00 63422179200
101 2009-11-20 00:00:00 63425894400
103 2008-05-20 00:00:00 63378460800
Advertisements