Summary: in this tutorial, you will learn how to use the MySQL TO_DAYS()
function to return the number of days since year 0 for a given date.
Introduction to the MySQL TO_DAYS() function
The TO_DAYS()
function allows you to get the number of days for since year 0 for a given date.
Here’s the syntax of the TO_DAYS()
function:
TO_DAYS(date)
Code language: SQL (Structured Query Language) (sql)
In this syntax:
The TO_DAYS()
function returns an integer that represents the number of days from the year 0 to the given date
. It returns NULL if the date argument is NULL.
MySQL TO_DAYS() function examples
Let’s take some examples of using the TO_DAYS()
function.
1) Using the TO_DAYS() function to convert a date to a numeric value
The following example uses the TO_DAYS()
function to get the number of days since year zero for the date 2023-10-23:
SELECT TO_DAYS('2023-10-23');
Code language: SQL (Structured Query Language) (sql)
Output:
+-----------------------+
| TO_DAYS('2023-10-23') |
+-----------------------+
| 739181 |
+-----------------------+
1 row in set (0.00 sec)
Code language: SQL (Structured Query Language) (sql)
The result is 739181 which represents the number of days from the year 0 to the specified date 2023-10-23.
2) Using the TO_DAYS() function to calculate the difference in days between two dates
The following example uses the TO_DAYS()
function to calculate the difference in days between two dates:
SELECT
TO_DAYS('2023-11-15') - TO_DAYS('2023-10-23') AS days_difference;
Code language: SQL (Structured Query Language) (sql)
Output:
+-----------------+
| days_difference |
+-----------------+
| 23 |
+-----------------+
1 row in set (0.01 sec)
Code language: SQL (Structured Query Language) (sql)
The function returns the number of days between two dates, ‘2023-10-23’ and ‘2023-11-15’, which in this case is 23 days.
Summary
- Use the
TO_DAYS()
function to return the number of days since year 0 for a given date.