The most useful Datetime functions
Function
NOW
Returns current date and time
SELECT 
    NOW()
Function
UNIX_TIMESTAMP
returns seconds since
1970-01-01 00:00:00
UTC
SELECT 
    UNIX_TIMESTAMP()
If any date is passed to the function as a parameter, it will calculate seconds since
1970-01-01 00:00:00
to the passed date. In this example, the function returns seconds to
2021-03-25
SELECT 
    UNIX_TIMESTAMP('2021-03-25')
Function
SYSDATE
Returns current date and time
SELECT 
    SYSDATE()
We can pass parameter
precision
to the function that indicates milliseconds and microseconds:
SELECT 
    SYSDATE(6)
Function
CURRENT_DATE
returns current date with the following syntax:
YYYY-MM-DD
SELECT 
    CURRENT_DATE()
Function
CURDATE
returns current date with the following syntax:
YYYY-MM-DD
SELECT 
    CURDATE()
Function
ADDDATE
adds some amount of time to the specified date
SELECT 
    ADDDATE('2021-03-25', INTERVAL 8 DAY)
Function
SUBDATE
subtracts some amount of time from the specified date
SELECT 
    SUBDATE('2021-03-25', INTERVAL 30 DAY)
Function
DATEDIFF
Calculates the number of days between the two parameters. In this example the function returns
12
which is the number of days between the dates
SELECT 
    DATEDIFF('2021-03-25', '2021-03-13')
The function returns
negative number
if the second date is greater than the first one. In the example the result will be
-12
SELECT 
    DATEDIFF('2021-03-13', '2021-03-25')
Function
TIMESTAMPDIFF
calculates the difference between two times. The result is in unites that we want to measure the difference between the times
SELECT 
    TIMESTAMPDIFF(DAY, '2021-03-13', '2021-03-25')
Function
MAKETIME
takes three parameters as hour, minute and time and returns formatted time like:
18:15:19
SELECT 
    MAKETIME(18, 15, 19)
Function
LAST_DAY
takes date and returns the last date of the month. In the example the result is
28
because the year is not leap year
SELECT 
    LAST_DAY('2021-02-15')
Function
DATE_FORMAT
returns formatted version of the datetime string passed as the first parameter
SELECT 
    DATE_FORMAT('2022-03-25 18:24:14', '%Y-%m-%d %H:%i:%s')
In this example we only need to get month and day with underscore between the values
SELECT 
    DATE_FORMAT('2022-03-25 18:24:14', '%m_%d')
by Valeri Tandilashvili
4 years ago
MySQL
1
Pro tip: use ```triple backticks around text``` to write in code fences