MySQL - TO_DAYS() Function



The MYSQL TO_DAYS() function accepts a date value as an argument and returns a numerical value representing the day number (the number of days since 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_DAYS() function −

TO_DAYS(date);

Parameters

This method accepts the date value from which you need to get the day of the month as a parameter.

Return value

This function returns a numerical value representing the day number (the number of days since year 0).

Example

In the following example, we are using the MySQL TO_DAYS() function to calculate the number of days from year 0000 to November 20, 2022 −

SELECT TO_DAYS('2022-11-20') As Result;

Output

This will produce the following result −

Result
738844

Example

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

SELECT TO_DAYS('2024-11-20 12:35:58') As Result;

Output

Following is the output −

Result
739575

Example

Following query calculates the number of days from year zero to the current date and returns the result −

SELECT TO_DAYS(CURDATE()) As Result;

Output

Following is the output −

Result
739209

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_DAYS() function to calculate the number of days since year 0 for each date value in the "DATE" column −

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

Output

The output is displayed as follows −

OID DATE Result
102 2009-10-08 00:00:00 734053
100 2009-10-08 00:00:0 734053
101 2009-11-20 00:00:00 734096
103 2008-05-20 00:00:00 733547
Advertisements