0% found this document useful (0 votes)
11 views34 pages

Data Science & Data Analyst - 16 - 7 - 2024 - 1721137033561 - SQL Date Function

The document provides an overview of various MySQL date and time functions, including CURDATE(), SYSDATE(), UTC_TIMESTAMP(), ADDTIME(), and DATE_ADD(). It explains their usage, syntax, and differences, such as how CURDATE() only returns the date while NOW() returns both date and time. Additionally, it includes examples demonstrating how to manipulate and convert time zones using these functions.

Uploaded by

shristygup1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views34 pages

Data Science & Data Analyst - 16 - 7 - 2024 - 1721137033561 - SQL Date Function

The document provides an overview of various MySQL date and time functions, including CURDATE(), SYSDATE(), UTC_TIMESTAMP(), ADDTIME(), and DATE_ADD(). It explains their usage, syntax, and differences, such as how CURDATE() only returns the date while NOW() returns both date and time. Additionally, it includes examples demonstrating how to manipulate and convert time zones using these functions.

Uploaded by

shristygup1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

MySQL CURDATE() function

The CURDATE() function returns the current date as a value in the 'YYYY-MM-DD' format if it is used in a
string context or YYYMMDD format if it is used in a numeric context.

The following example shows how the CURDATE() function is used in the string context.

mysql> SELECT CURDATE();


+------------+
| CURDATE() |
+------------+
| 2017-07-13 |
+------------+
1 row in set (0.00 sec)

The following example illustrates how the CURDATE() function is used in a numeric context:

mysql> SELECT CURDATE() + 0;


+---------------+
| CURDATE() + 0 |
+---------------+
| 20170713 |
+---------------+
1 row in set (0.04 sec)

The CURRENT_DATE and CURRENT_DATE() are synonyms for CURDATE().

mysql> SELECT CURRENT_DATE(),


CURRENT_DATE,
CURDATE();
+----------------+--------------+------------+
| CURRENT_DATE() | CURRENT_DATE | CURDATE() |
+----------------+--------------+------------+
| 2017-07-13 | 2017-07-13 | 2017-07-13 |
+----------------+--------------+------------+
1 row in set (0.00 sec)

CURDATE vs. NOW

The CURDATE() function returns the current date with the date part only while the NOW() function returns
both date and time parts of the current time.

The result of the CURDATE() function is equivalent to the following expression:

mysql> SELECT DATE(NOW());


+-------------+
| DATE(NOW()) |
+-------------+
| 2017-07-13 |
+-------------+
1 row in set (0.00 sec)

MySQL SYSDATE() function


The SYSDATE() function returns the current date and time at which it is executed. If you
use the function in the string context, the return value in the 'YYYY-MM-DD
HH:MM:SS' format. However, if you use the function in a numeric context, it returns a
value in the YYYYMMDDHHMMSS format.
Here’s the basic syntax of the SYSDATE() function:
SYSDATE(fsp);
The SYSDATE() function accepts an optional argument fsp that determines whether the
result should include a fractional seconds precision which ranges from 0 to 6.

See the following example:

SELECT SYSDATE();

Output:

+---------------------+
| SYSDATE() |
+---------------------+
| 2017-07-13 17:42:37 |
+---------------------+
1 row in set (0.00 sec)
If you pass the fsp argument, the result will include the fractional seconds precision as
shown in the following example:
SELECT SYSDATE(3);

Output:

+-------------------------+
| SYSDATE(3) |
+-------------------------+
| 2017-07-13 17:42:55.875 |
+-------------------------+
1 row in set (0.00 sec)

SYSDATE vs. NOW

The following example uses the SYSDATE() and NOW() functions in the same query:
SELECT
SYSDATE(),
NOW();

Output:

+---------------------+---------------------+
| SYSDATE() | NOW() |
+---------------------+---------------------+
| 2017-07-13 17:46:30 | 2017-07-13 17:46:30 |
+---------------------+---------------------+
1 row in set (0.00 sec)
It seems that both SYSDATE() and NOW() functions return the same value which is the
current date and time at which it is executed.
However, the SYSDATE() function actually returns the time at which it executes while
the NOW() function returns a constant time at which the statement began to execute. For
example:
SELECT
NOW(),
SLEEP(5),
NOW();

Output:

+---------------------+----------+---------------------+
| NOW() | SLEEP(5) | NOW() |
+---------------------+----------+---------------------+
| 2017-07-13 17:49:18 | 0 | 2017-07-13 17:49:18 |
+---------------------+----------+---------------------+
1 row in set (5.00 sec)
In this example, we use the SLEEP() function to pause the query for 5 seconds. Within the
same statement, the NOW() function always returns a constant which is the time at
which the statement starts.
Let’s change the NOW() function to SYSDATE() function:
SELECT
SYSDATE(),
SLEEP(5),
SYSDATE();

Output:

+---------------------+----------+---------------------+
| SYSDATE() | SLEEP(5) | SYSDATE() |
+---------------------+----------+---------------------+
| 2017-07-13 17:50:57 | 0 | 2017-07-13 17:51:02 |
+---------------------+----------+---------------------+
1 row in set (5.00 sec)

MySQL UTC_TIMESTAMP() function

The UTC_TIMESTAMP() function returns the current coordinated universal time


(UTC) date and time.
Here’s the syntax of the UTC_TIMESTAMP() function:
UTC_TIMESTAMP()
The UTC_TIMESTAMP() doesn’t require any arguments and returns the current UTC date
and time.
In practice, you’ll use the UTC_TIMESTAMP() function to work with date and time values
in a timezone-independent manner.

MySQL UTC_TIMESTAMP() function examples

Let’s take some examples of using the UTC_TIMESTAMP() function.


1) Simple UTC_TIMESTAMP() function example
The following example uses the UTC_TIMESTAMP() to get the current UTC time:
SELECT UTC_TIMESTAMP() AS current_utc_time;

Output:

+---------------------+
| current_utc_time |
+---------------------+
| 2023-10-17 06:49:00 |
+---------------------+
1 row in set (0.00 sec)

Finally, query data from the activity_logs table and convert the time values of the events
to US/Eastern timezone:
SELECT
description,
CONVERT_TZ(time, 'UTC', 'US/Eastern') AS time
FROM
activity_logs;

Output:

+----------------+---------------------+
| description | time |
+----------------+---------------------+
| User logged in | 2023-10-17 04:17:21 |
| File uploaded | 2023-10-17 04:17:21 |
| Data processed | 2023-10-17 04:17:21 |
+----------------+---------------------+
3 rows in set (0.01 sec)
Note that if you see the NULL values in the time column, it’s likely that your database
server is not configured with the timezone properly.
convert_tz(currenttime,from,to)
Ex
SELECT convert_tz(now(),"+5:30","+5:00")

List of Timezones
Following is the list of various time zones −

S.NO Name & Description Relative to GMT

1 GMT GMT
Greenwich Mean Time

2 UTC GMT
Universal Coordinated Time

3 ECT GMT+1:00
European Central Time

4 EET GMT+2:00
Eastern European Time

5 ART GMT+2:00
(Arabic) Egypt Standard Time

6 EAT GMT+3:00
Eastern African Time

7 MET GMT+3:30
Middle East Time

8 NET GMT+4:00
Near East Time

9 PLT GMT+5:00
Pakistan Lahore Time

10 IST GMT+5:30
India Standard Time

11 BST GMT+6:00
Bangladesh Standard Time

12 VST GMT+7:00
Vietnam Standard Time

13 CTT GMT+8:00
China Taiwan Time

14 JST GMT+9:00
Japan Standard Time

15 ACT GMT+9:30
Australia Central Time

16 AET GMT+10:00
Australia Eastern Time

17 SST GMT+11:00
Solomon Standard Time

18 NST GMT+12:00
New Zealand Standard Time

19 MIT GMT-11:00
Midway Islands Time

20 HST GMT-10:00
Hawaii Standard Time

21 AST GMT-9:00
Alaska Standard Time

22 PST GMT-8:00
Pacific Standard Time
23 PNT GMT-7:00
Phoenix Standard Time

24 MST GMT-7:00
Mountain Standard Time

25 CST GMT-6:00
Central Standard Time

26 EST GMT-5:00
Eastern Standard Time

27 IET GMT-5:00
Indiana Eastern Standard Time

28 PRT GMT-4:00
Puerto Rico and US Virgin Islands Time

29 CNT GMT-3:30
Canada Newfoundland Time

30 AGT GMT-3:00
Argentina Standard Time

31 BET GMT-3:00
Brazil Eastern Time

32 CAT GMT-1:00
Central African Time

MySQL ADDTIME() function

The ADDTIME() function allows you to add a time interval to


a time or datetime expression. Here’s the syntax of the ADDTIME() function:
ADDTIME(datetime, time_interval)

In this syntax:

 datetime: The initial datetime or time value you want to add the time interval.
 time_interval: The time interval you want to add, specified as a time expression in
the format ‘HH:MM:SS‘.

In practice, you often use the ADDTIME() function to add hours, minutes, or seconds to a
timestamp.

MySQL ADDTIME() function examples


Let’s take some examples of using the ADDTIME() function.
1) Basic MySQL ADDTIME() function example
The following example uses the ADDTIME() function to add 3 hours, 30 minutes, and 45
seconds to the date time ‘2023-10-23 14:30:00’:
SELECT ADDTIME('2023-10-23 14:30:00', '03:30:45');

Output:

+--------------------------------------------+
| ADDTIME('2023-10-23 14:30:00', '03:30:45') |
+--------------------------------------------+
| 2023-10-23 18:00:45 |
+--------------------------------------------+
1 row in set (0.01 sec)
2) Adding Minutes to a Time Value
The following example uses the ADDTIME() function to add 15 minutes to a time value
that represents the duration of a meeting:
SELECT ADDTIME('00:30:00', '00:15:00');

Output:

+---------------------------------+
| ADDTIME('00:30:00', '00:15:00') |
+---------------------------------+
| 00:45:00 |
+---------------------------------+
1 row in set (0.00 sec)

The result is ’00:45:00′, which represents the updated meeting duration.

3) Using the ADDTIME() function with negative time intervals


The ADDTIME() function allows you to subtract a time by using negative time intervals.

For example, if you have a time value representing the duration of a break and you want
to subtract 10 minutes from it:

SELECT ADDTIME('00:15:00', '-00:10:00');

Output:

+----------------------------------+
| ADDTIME('00:15:00', '-00:10:00') |
+----------------------------------+
| 00:05:00 |
+----------------------------------+
1 row in set (0.00 sec

The result is ’00:05:00′ which indicates the new duration after subtracting 10 minutes.

MySQL DATE_ADD function


The DATE_ADD function adds an interval to a DATE or DATETIME value.
The following illustrates the syntax of the DATE_ADD function:
DATE_ADD(start_date, INTERVAL expr unit);
The DATE_ADD function takes two arguments:

 start_date is a starting DATE or DATETIME value.


 INTERVAL expr unit is an interval value to be added to the starting date value.

The DATE_ADD() function may return a DATETIME value or a string, depending on the
arguments:

 DATETIME if the first argument is a DATETIME value or if the interval value has a
time element such as hour, minute, second, etc.
 String otherwise.
MySQL DATE_ADD function

examples

Let’s take a look at some examples to understand how DATE_ADD() function works.
The following statement uses the DATE_ADD() function to add one second to 1999-12-31
23:59:59:
SELECT
DATE_ADD('1999-12-31 23:59:59',
INTERVAL 1 SECOND) result;

Output:

+---------------------+
| result |
+---------------------+
| 2000-01-01 00:00:00 |
+---------------------+
1 row in set (0.00 sec) script)
The following example uses the DATE_ADD() function to add one day to 1999-12-31
00:00:01:
SELECT
DATE_ADD('1999-12-31 00:00:01',
INTERVAL 1 DAY) result;

Output:

+---------------------+
| result |
+---------------------+
| 2000-01-01 00:00:01 |
+---------------------+
1 row in set (0.00 sec) script)
The following example uses the DATE_ADD() function to add 1 minute and 1 second
to 1999-12-31 23:59:59:
SELECT
DATE_ADD('1999-12-31 23:59:59',
INTERVAL '1:1' MINUTE_SECOND) result;

Output:

+---------------------+
| result |
+---------------------+
| 2000-01-01 00:01:00 |
+---------------------+
1 row in set (0.00 sec) script)
The following example adds -1 day and 5 hours to 2000-01-01 00:00:00.
SELECT DATE_ADD('2000-01-01 00:00:00',
INTERVAL '-1 5' DAY_HOUR) result;

Output:

+---------------------+
| result |
+---------------------+
| 1999-12-30 19:00:00 |
+---------------------+
1 row in set (0.00 sec) script)
The following example adds 1 second and 999999 microseconds to 1999-12-31
23:59:59.000002:
SELECT
DATE_ADD('1999-12-31 23:59:59.000002',
INTERVAL '1.999999' SECOND_MICROSECOND) result;

Output:

+----------------------------+
| result |
+----------------------------+
| 2000-01-01 00:00:01.000001 |
+----------------------------+
1 row in set (0.00 sec) script)

MySQL DATE_ADD function usage notes

Interval Handling

In the interval:

INTERVAL expr unit


The expr is treated as a string, therefore, you should be careful when you use a non-
string value for the expr.
For example, with an interval of HOUR_MINUTE, 5/2 evaluates to 2.5000 (not 2.5) and is
treated as 2 hours 5000 minutes as in the following statement:
SELECT
DATE_ADD('2000-01-01',
INTERVAL 5 / 2 HOUR_MINUTE) result;
Output:

+---------------------+
| result |
+---------------------+
| 2000-01-04 13:20:00 |
+---------------------+
1 row in set (0.00 sec) script)
To ensure the correct interpretation of a non-string interval value, you should use
the CAST function as follows:
SELECT
DATE_ADD('2000-01-01',
INTERVAL CAST(6/4 AS DECIMAL(3,1)) HOUR_MINUTE) result;

Output:

+---------------------+
| result |
+---------------------+
| 2000-01-01 01:05:00 |
+---------------------+
1 row in set (0.00 sec)
script)
Automatic DATETIME conversion
If you add a time value to a date value, the result is a DATETIME value as shown in the
following example:
SELECT
DATE_ADD('2000-01-01', INTERVAL 12 HOUR) result;

Output:

+---------------------+
| result |
+---------------------+
| 2000-01-01 12:00:00 |
+---------------------+
1 row in set (0.00 sec) script)
Invalid starting date
The DATE_ADD function returns NULL if you use an invalid date for the first argument, for
example:
SELECT DATE_ADD('2000-02-30',
INTERVAL 1 DAY) result;

Output:

+--------+
| result |
+--------+
| NULL |
+--------+
1 row in set, 1 warning (0.00 sec) script)
If you want to see the warning in detail, you use the SHOW WARNINGS statement:
SHOW WARNINGS;

Output:

+---------+------+----------------------------------------+
| Level | Code | Message |
+---------+------+----------------------------------------+
| Warning | 1292 | Incorrect datetime value: '2000-02-30' |
+---------+------+----------------------------------------+
1 row in set (0.00 sec) script)
Adjusted day, month, or year
If you add an interval of MONTH, YEAR, or YEAR_MONTH to a date that results in a date
that has a day larger than the maximum day for the new month, the day will be adjusted
to the maximum day in the new month.

Consider the following example:

SELECT
DATE_ADD('2010-01-30',
INTERVAL 1 MONTH) result;

Output:

+------------+
| result |
+------------+
| 2010-02-28 |
+------------+
1 row in set (0.00 sec) script)
In this example, we added 1 month to the January 30th 2010 that results in February
28th 2010. The day was adjusted to the maximum day inFebruary 2010.

In the year that February has 29 days, the date will be also adjusted to the 29th as
shown below:

SELECT
DATE_ADD('2012-01-30',
INTERVAL 1 MONTH) result;

Output:

+------------+
| result |
+------------+
| 2012-02-29 |
+------------+
1 row in set (0.00 sec)

MySQL DATE_SUB() function

The DATE_SUB() function subtracts a time value (or an interval) from


a DATE or DATETIME value.

Here’s the syntax of the DATE_SUB() function:

DATE_SUB(date,INTERVAL expr unit)


The DATE_SUB() function accepts two arguments:

 date: This is the date that you want to subtract a value.


 expr: This is a string that determines an interval value that you want to subtract
from the date. The unit is the interval unit that expr should be interpreted
e.g., DAY, HOUR, etc.

The DATE_SUB() function returns NULL if the date is NULL.

The following statement uses the DATE_SUB() function to subtract one day from the July-
4th-2017:

SELECT DATE_SUB('2017-07-04',INTERVAL 1 DAY) result;

Output:

+------------+
| result |
+------------+
| 2017-07-03 |
+------------+
1 row in set (0.00 sec) script)

In this example:

 The date is 2017-07-04, which is in the yyyy-mm-dd format.


 The INTERVAL 1 DAY is interpreted as 1 day interval.

MySQL DATEDIFF() function

The DATEDIFF() function calculates the difference in days between two dates.
Here’s the basic syntax of the DATEDIFF() function:
DATEDIFF(end_date,start_date);

In this syntax:

 end_date: The date to which you want to calculate the difference.


 start_date: The date from which you want to calculate the difference.

The DATEDIFF() function returns an integer that represents the number of days between
two dates.
If end_date or start_date is NULL, the DATEDIFF() function returns NULL.
Notice that the DATEDIFF() function considers only the date components for calculation
and disregards the time components.

MySQL DATEDIFF examples

Let’s take some examples of using the DATEDIFF() function


1) Simple DATEDIFF() function example
The following example uses the DATEDIFF() function to calculate the difference between
two DATE literal values:
SELECT
DATEDIFF('2011-08-17', '2011-08-17') days;
https://www.mysqltutorial.org/tryit/query/mysql-datediff/ - 1

Output:

+------+
| days |
+------+
| 0|
+------+
1 row in set (0.00 sec)Code langu

MySQL TIMEDIFF() function

The TIMEDIFF() function calculates the difference between two TIME or DATETIME values.
Here’s the syntax of TIMEDIFF() function:
TIMEDIFF(time1, time2);

In this syntax:

 time1: The first TIME or DATETIME value.


 time2: The second TIME or DATETIME value.

The TIMEDIFF() function returns the difference between two TIME values (time1 - time2)
in the format 'HH:MM:SS'.
Because the TIMEDIFF() function returns a TIME value, its result is limited to the range
allowed for TIME values which are from -838:59:59 to 838:59:59.
If time1 or time2 is NULL, the TIMEDIFF() function returns NULL.
It’s important to note that the TIMEDIFF() function accepts values
with TIME or DATETIME types. To calculate the difference between
two DATE or DATETIME values, you use the DATEDIFF() function.

MySQL TIMEDIFF function examples

Let’s take an example that calculates the difference between two TIME values.

1) Simple TIMEDIFF function example


The following example uses the TIMEDIFF() function to calculate the difference between
two literal time values:
SELECT TIMEDIFF('12:00:00','10:00:00') diff; script)

Output:

+----------+
| diff |
+----------+
| 02:00:00 |
+----------+
1 row in set (0.00 sec)
The query returns the time difference between '12:00:00' and '10:00:00', which
is '02:00:00'.

MySQL TIMESTAMPADD() function


The TIMESTAMPADD() function allows you to add or subtract intervals from a timestamp or date.
Here’s the syntax of the TIMESTAMPADD() function:
TIMESTAMPADD(unit, interval, timestamp)

In this syntax:

 unit: This is the unit of time that you want to add


(e.g., SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, YEAR).
 interval: This is the number of intervals you want to add (can be a positive or negative integer).
 timestamp: This is the timestamp or date to which you want to add the interval.

The TIMESTAMPADD() function returns a new date or timestamp with the new.
It returns NULL if interval or timestamp is NULL.

MySQL TIMESTAMPADD() function examples

Let’s take some examples of using the MySQL TIMESTAMPADD() function.


1) Basic usage of TIMESTAMPADD() function example
The following example uses the TIMESTAMPADD() function to add days to a given timestamp:
SELECT
TIMESTAMPADD(DAY, 7, '2023-10-19 15:30:00') AS new_timestamp

Output:

+---------------------+
| new_timestamp |
+---------------------+
| 2023-10-26 15:30:00 |
+---------------------+
1 row in set (0.01 sec)
In this example, we use the TIMESTAMPADD() function to add seven days to the timestamp '2023-10-19
15:30:00'.
2) Using TIMESTAMPADD() with different intervals
The following example uses the TIMESTAMPADD() function to add three months to the date '2022-07-15':
SELECT
TIMESTAMPADD(MONTH, 3, '2022-07-15') AS new_date;

Output:

+------------+
| new_date |
+------------+
| 2022-10-15 |
+------------+
1 row in set (0.00 sec)

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)
In this syntax:

 date: The date or datetime value that you want to calculate the number of days
since year 0.

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');

Output:

+-----------------------+
| TO_DAYS('2023-10-23') |
+-----------------------+
| 739181 |
+-----------------------+
1 row in set (0.00 sec)

MySQL CONVERT_TZ() function

The CONVERT_TZ() function allows you to convert a datetime value from one timezone to
another.
Here’s the syntax of the CONVERT_TZ() function:
CONVERT_TZ(datetime, from_tz, to_tz)

In this syntax:

 datetime: The datetime value you want to convert.


 from_tz: The source time zone.
 to_tz: The target time zone.

The CONVERT_TZ() function returns a datetime value converted from the source time
zone to the target timezone.
The CONVER_TZ() function returns NULL if any argument is NULL or invalid.
The CONVERT_TZ() function can be useful for applications that manage date and time
from different time zones, for example, international flight schedules and global event
planning.
To use the CONVERT_TZ() function, you need to load data into the time zone tables.

MySQL CONVER_TZ() function examples

Let’s take some examples of using the CONVERT_TZ() function.


1) Basic time zone conversion example
The following example uses the CONVERT_TZ() function to convert a datetime value
from UTC to 'America/New_York' timezone:
SELECT
CONVERT_TZ(
'2023-04-15 15:30:00', 'UTC', 'America/New_York'
) NYTime;

Output:

+---------------------+
| NYTime |
+---------------------+
| 2023-04-15 11:30:00 |
+---------------------+
1 row in set (0.00 sec)

MySQL FROM_DAYS() function

The FROM_DAYS() function returns a numeric day count into a date.

Here’s the syntax for the FROM_DAYS() function:

FROM_DAYS(days)

In this syntax:

 days: This parameter is the number of days since '0000-00-00' that you want to
convert into a date.

In practice, you use the function when working with date data stored as the number of
days since the date '0000-00-00'.

MySQL FROM_DAYS() function example

The following example uses the FROM_DAYS() function to convert a numeric day count
into a date:

SELECT
FROM_DAYS(737989) AS converted_date;

Output:

+----------------+
| converted_date |
+----------------+
| 2020-07-18 |
+----------------+
1 row in set (0.00 sec)
MySQL STR_TO_DATE function

The STR_TO_DATE() converts a string into a date value based on a specified format
string.

Here’s the syntax of the STR_TO_DATE() function:

STR_TO_DATE(str,fmt);

In this syntax:

 str: This is the input string that you want to convert.


 fmt: This is the format string that includes format specifiers. For example, %d for
day, %m for month and %y for year.

The STR_TO_DATE() function may return a DATE , TIME, or DATETIME value based on the
input and format strings.

If the input string is illegal, the STR_TO_DATE() function returns NULL.

The STR_TO_DATE() function scans the input string to match the format string. The
format string may contain literal characters and format specifiers that begin with a
percentage (%) character.

Refer to the DATE_FORMAT function for the list of format specifiers.

The STR_TO_DATE() function is very useful in data migration that involves temporal data
conversion from an external format to MySQL temporal data format.
MySQL DATE_FORMAT function

To format a date value to a specific format, you use the DATE_FORMAT() function. The
syntax of the DATE_FORMAT function is as follows:

DATE_FORMAT(date,format)

The DATE_FORMAT() function accepts two arguments:

 date : is a valid date value that you want to format


 format : is a format string that consists of predefined specifiers. Each specifier is
preceded by a percentage character ( % ). See the table below for a list of
predefined specifiers.

The DATE_FORMAT function returns a string whose character set and collation depend on
the settings of the client’s connection.

The following table illustrates the specifiers and their meanings that you can use to
construct a date format string:

Specifier Meaning
%a Three-characters abbreviated weekday name e.g., Mon, Tue, Wed, etc.
%b Three-characters abbreviated month name e.g., Jan, Feb, Mar, etc.
%c Month in numeric e.g., 1, 2, 3…12
%D Week number with leading zero when the first day of the week is Sunday e.g., 00,01,02…53
%d Day of the month with leading zero if it is 1 number e.g., 00, 01,02, …31
%e Day of the month without leading zero e.g., 1,2,…31
%f Microseconds in the range of 000000..999999
%H Hour in 24-hour format with leading zero e.g., 00..23
%h Hour in 12-hour format with leading zero e.g., 01, 02…12
%I Same as %h
%i Minutes with leading zero e.g., 00, 01,…59
%j Day of year with leading zero e.g., 001,002,…366
%k Hour in 24-hour format without leading zero e.g., 0,1,2…23
%l Hour in 12-hour format without leading zero e.g., 1,2…12
%M Full month name e.g., January, February,…December
%m Month name with leading zero e.g., 00,01,02,…12
%p AM or PM, depending on other time specifiers
%r Time in 12-hour format hh:mm:ss AM or PM
%S Seconds with leading zero 00,01,…59
%s Same as %S
%T Time in 24-hour format hh:mm:ss
%U Weekday in number (0=Sunday, 1= Monday, etc.)
%u Week number with leading zero when the first day of the week is Monday e.g., 00,01,02…53
%V Same as %U; it is used with %X
%v Same as %u; it is used with %x
%W Full name of weekday e.g., Sunday, Monday,…, Saturday
%w Two digits year e.g., 10,11, and 12.
%X Year for the week in four digits where the first day of the week is Sunday; often used with %V
%x Year for the week, where the first day of the week is Monday, four digits; used with %v
Specifier Meaning
%Y Four digits year e.g., 2000 and 2001.
%y Add a percentage (%) character to the output
%% Add percentage (%) character to the output

The following are some commonly used date format strings:

DATE_FORMAT string Formatted date


%Y-%m-%d 2013-07-04
%e/%c/%Y 4/7/2013
%c/%e/%Y 7/4/2013
%d/%m/%Y 4/7/2013
%m/%d/%Y 7/4/2013
%e/%c/%Y %H:%i 4/7/2013 11:20
%c/%e/%Y %H:%i 7/4/2013 11:20
%d/%m/%Y %H:%i 4/7/2013 11:20
%m/%d/%Y %H:%i 7/4/2013 11:20
%e/%c/%Y %T 4/7/2013 11:20
%c/%e/%Y %T 7/4/2013 11:20
%d/%m/%Y %T 4/7/2013 11:20
%m/%d/%Y %T 7/4/2013 11:20
%a %D %b %Y Thu 4th Jul 2013
%a %D %b %Y %H:%i Thu 4th Jul 2013 11:20
%a %D %b %Y %T Thu 4th Jul 2013 11:20:05
%a %b %e %Y Thu Jul 4 2013
%a %b %e %Y %H:%i Thu Jul 4 2013 11:20
%a %b %e %Y %T Thu Jul 4 2013 11:20:05
%W %D %M %Y Thursday 4th July 2013
%W %D %M %Y %H:%i Thursday 4th July 2013 11:20
%W %D %M %Y %T Thursday 4th July 2013 11:20:05
%l:%i %p %b %e, %Y 7/4/2013 11:20
%M %e, %Y 4-Jul-13
%a, %d %b %Y %T Thu, 04 Jul 2013 11:20:05

MySQL DATE_FORMAT examples

Let’s take a look at the orders table in the sample database.

To select the order’s data and format the date value, you use the following statement:

SELECT
orderNumber,
DATE_FORMAT(orderdate, '%Y-%m-%d') orderDate,
DATE_FORMAT(requireddate, '%a %D %b %Y') requireddate,
DATE_FORMAT(shippedDate, '%W %D %M %Y') shippedDate
FROM
orders;

https://www.mysqltutorial.org/tryit/query/mysql-date_format/ - 1
MySQL STR_TO_DATE examples

Let’s look at some examples of using STR_TO_DATE() function to convert strings into date
and/or time values

The following statement converts a string into a DATE value.

SELECT STR_TO_DATE('21,5,2013','%d,%m,%Y');

Output:

+-------------------------------------+
| STR_TO_DATE('21,5,2013','%d,%m,%Y') |
+-------------------------------------+
| 2013-05-21 |
+-------------------------------------+
1 row in set (0.00 sec)

MySQL DATE() function

The DATE() function allows you to extract the date component from
a datetime or timestamp expression.
Here’s the syntax of the DATE() function:
DATE(expression)

In this syntax:

 expression: This is an expression that evaluates to a DATE, a DATETIME, or


a TIMESTAMP value from which you want to extract the value.

The DATE() function returns the DATE value. It returns NULL if the expression is NULL.
The DATE() function is a convenient tool for working
with DATETIME and TIMESTAMP values in the database. It allows you to extract, filter,
group, and perform date arithmetic on date expressions. By using the DATE() function in
your queries, you can manage and analyze date-related data more effectively.
MySQL DATE() function examples

Let’s take some examples of using the MySQL DATE() function.


1) Extracting a date from a DATETIME value
The following example uses the DATE() function to extract the date from
a DATETIME literal value:
SELECT DATE('2023-10-17 14:30:45');

Output:

+-----------------------------+
| DATE('2023-10-17 14:30:45') |
+-----------------------------+
| 2023-10-17 |
+-----------------------------+
1 row in set (0.00 sec)
In this example, the DATE() function returns a DATE value ('2023-10-17') from
the DATETIME value '2023-10-17 14:30:45'.

MySQL EXTRACT() function

The EXTRACT() function extracts part of a date. The following illustrates the syntax of
the EXTRACT() function.

EXTRACT(unit FROM date)

The EXTRACT() function requires two arguments unit and date.

The unit is the interval that you want to extract from the date. The following are the valid
intervals for the unit argument.

 DAY
 DAY_HOUR
 DAY_MICROSECOND
 DAY_MINUTE
 DAY_SECOND
 HOUR
 HOUR_MICROSECOND
 HOUR_MINUTE
 HOUR_SECOND
 MICROSECOND
 MINUTE
 MINUTE_MICROSECOND
 MINUTE_SECOND
 MONTH
 QUARTER
 SECOND
 SECOND_MICROSECOND
 WEEK
 YEAR
 YEAR_MONTH

The date is a DATE or DATETIME value from which you extract an interval.

MySQL EXTRACT() function examples

Extract day from a datetime:


mysql> SELECT EXTRACT(DAY FROM '2017-07-14 09:04:44') DAY;
+------+
| DAY |
+------+
| 14 |
+------+
1 row in set (0.00 sec)

Extract day_hour from a datetime:

mysql> SELECT EXTRACT(DAY_HOUR FROM '2017-07-14 09:04:44') DAYHOUR;


+---------+
| DAYHOUR |
+---------+
| 1409 |
+---------+
1 row in set (0.00 sec)

Extract day_microsecond from a datetime:

mysql> SELECT EXTRACT(DAY_MICROSECOND FROM '2017-07-14 09:04:44') DAY_MS;


+----------------+
| DAY_MS |
+----------------+
| 14090444000000 |
+----------------+
1 row in set (0.00 sec)

Extract day_minute from a datetime:

mysql> SELECT EXTRACT(DAY_MINUTE FROM '2017-07-14 09:04:44') DAY_M;


+--------+
| DAY_M |
+--------+
| 140904 |
+--------+
1 row in set (0.00 sec)

Extract day_second from a datetime

mysql> SELECT EXTRACT(DAY_SECOND FROM '2017-07-14 09:04:44') DAY_S;


+----------+
| DAY_S |
+----------+
| 14090444 |
+----------+
1 row in set (0.00 sec)
MySQL YEAR() function

The YEAR() function returns a year from a date value. Here’s the basic syntax of
the YEAR() function:
YEAR(date);

In this syntax:

 date: This is the date or datetime value from which you want to get the year.

The YEAR() function returns an integer that represents the year part of the provided
date. It has a range of 1000 and 9999.
If the date is zero, the YEAR() function returns 0. If the date is NULL, the YEAR() function
returns NULL.

MySQL YEAR() function examples

Let’s take some examples of using the YEAR() function.


1) Simple YEAR() function examples
The following example uses the YEAR() function to extract the year of January 1st 2017:
SELECT YEAR('2017-01-01'); script)

Output:

+--------------------+
| YEAR('2017-01-01') |
+--------------------+
| 2017 |
+--------------------+
1 row in set (0.00 sec)

MySQL YEARWEEK() function

The YEARWEEK() function returns the year and week for a date.
Here’s the syntax of the YEARWEEK() function:
YEARWEEK(date)

In this syntax:

 date: This is the date from which you want to extract the year and week.

The YEARWEEK returns a value in the format yw format. e.g., 202312, 2023 is the year
and 12 is the week number. The YEARWEEK() function returns NULL if the date is NULL.
The YEARKWEEK() function also accepts a second argument:
YEARWEEK(date,mode)
In this syntax, the mode argument specifies whether the return value should start in the
range from 0 to 53 or from 1 to 53.
If you omit the mode argument, the YEARWEEK() function uses the value of the system
variable @@default_week_format:
SELECT @@default_week_format;

Output:
+-----------------------+
| @@default_week_format |
+-----------------------+
| 0|
+-----------------------+
1 row in set (0.00 sec)

The output shows that the default week format is 0, meaning that the first day of the
week is Sunday, and the range for the week is from 0 to 53.

The following table shows all the valid modes that you can use:

Mode First Day of Week Range Week 1 is the first week when…

0 Sunday 0-53 with Sunday in this year Any Sunday in the year

1 Monday 0-53 with 4 or more days this year At least 4 days fall within the year

2 Sunday 1-53 with Sunday in this year Any Sunday in the year, starting from w

3 Monday 1-53 with 4 or more days this year At least 4 days fall within the year, star

4 Sunday 0-53 with 4 or more days this year Any Sunday in the year, starting from w

5 Monday 0-53 with Monday in this year Any Monday in the year

6 Sunday 1-53 with 4 or more days this year At least 4 days fall within the year, star

7 Monday 1-53 with Monday in this year Any Monday in the year, starting from

MySQL YEARWEEK function examples

We’ll take some examples of using the MySQL YEARWEEK() function.


1) Simple YEARWEEK() function example
The following example uses the YEARWEEK() function to get the year and week of the
date ‘2023-10-17’:
SELECT YEARWEEK('2023-01-01');

Output:

+------------------------+
| YEARWEEK('2023-01-01') |
+------------------------+
| 202301 |
+------------------------+
1 row in set (0.00 sec)
It returns 202342 where 2023 is the year and 01 is the week number.
2) The YEARWEEK() function example with the mode argument
The following example uses the YEARWEEK() function with the mode 3. It returns a
different result based on the rule of the mode 3:
SELECT YEARWEEK('2023-01-01',3);

Output:

+--------------------------+
| YEARWEEK('2023-01-01',3) |
+--------------------------+
| 202252 |
+--------------------------+
1 row in set (0.00 sec)

Summary

 Use the MySQL YEARWEEK() function to return year and week for a date.

MySQL QUARTER() function

The QUARTER() function allows you to get the quarter of the year for a specific date.
Here’s the syntax of the QUARTER() function:
QUARTER(date)

In this syntax:

 date: This is the date for which you want to get the quarter.

The QUARTER() function returns an integer from 1 to 4, which represents the quarter of
the year for the date.
If the date is NULL, the QUARTER() function returns NULL.
The QUARTER() function is useful in data analytic applications. For example, you can use
it in the sales and finance application to analyze the sales, revenues, and expenses by
quarters.

MySQL QUARTER() function examples

Let’s take some examples of using the QUARTER() function.


1) Simple QUARTER() function example
The following example uses the QUARTER() function to return the quarter of the
date '2023-10-18':
SELECT QUARTER('2023-10-18');

Output:

+-----------------------+
| quarter('2023-10-18') |
+-----------------------+
| 4|
+-----------------------+
1 row in set (0.01 sec)

MONTH() function

The MONTH function returns an integer that represents the month of a specified date.
The following illustrates the syntax of the MONTH function:
MONTH(date);
The MONTH function accepts one argument which is a DATE or DATETIME value. It
returns an integer that ranges from 1 to 12, which represents January to December.
The MONTH() function returns NULL if the date is NULL. Also, it returns zero, if the date is
zero (0000-00-00).

MySQL MONTH() function examples


Let’s take some examples of using the MONTH() function

1) Simple Month() function examples


The following example uses the MONTH() function to get the month of 2010-01-01:
SELECT MONTH('2010-01-01'); script)

Output:

+---------------------+
| MONTH('2010-01-01') |
+---------------------+
| 1|
+---------------------+
1 row in set (0.00 sec)

MySQL WEEK() function

Typically, a year has 365 days for a normal year and 366 days for a leap year. A year is
then divided into weeks with each week having exactly 7 days. So for a year we often
has 365 / 7 = 52 weeks that range from 1 to 52.

The WEEK() function allows you to get the week number of a specific date:

WEEK(date, mode);

In this syntax:

 date: This is the date that you want to get a week number.
 mode: This is an optional argument that determines how the function calculates
the week number. It specifies whether the week should start on Monday or
Sunday and the returned week number should be between 0 and 52 or 0 and 53.

The WEEK() function returns a week number based on ISO 8601:1988.


If you ignore the mode argument, the WEEK() function will use the value of
the default_week_format system variable by default.
To get the current value of default_week_format variable, you use the SHOW
VARIABLES statement as follows:
SHOW VARIABLES LIKE 'default_week_format'; script)

Output:

+---------------------+-------+
| Variable_name | Value |
+---------------------+-------+
| default_week_format | 0 |
+---------------------+-------+
1 row in set (0.01 sec)
The output shows that the default value of default_week_format is 0.
The following table illustrates how the mode argument influences the WEEK function:
Mode First day of week Range Week 1 is the first week …

0 Sunday 0-53 with a Sunday in this year


Mode First day of week Range Week 1 is the first week …

1 Monday 0-53 with 4 or more days this year

2 Sunday 1-53 with a Sunday in this year

3 Monday 1-53 with 4 or more days this year

4 Sunday 0-53 with 4 or more days this year

5 Monday 0-53 with a Monday in this year

6 Sunday 1-53 with 4 or more days this year

7 Monday 1-53 with a Monday in this year

The ” with 4 or more days this year” in the above table means:

 If the week contains January 1st and has 4 or more days in the new year, the
week is numbered as week 1.
 Otherwise, the week is numbered as the last week of the previous year and the
next week is week 1.

MySQL WEEK() function example

Let’s take some examples of using the WEEK() function.


1) Simple MySQL WEEK() function example
The following example uses the WEEK() function to get the week number of the
date '2023-10-16':
SELECT WEEK('2023-10-16') as week_no; script)

Output:

+---------+
| week_no |
+---------+
| 42 |
+---------+
1 row in set (0.01 sec)

MySQL WEEKDAY() function

The WEEKDAY() function returns a weekday index for a date i.e., 0 for Monday, 1 for
Tuesday, … 6 for Sunday.
Here’s the syntax of the WEEKDAY() function:
WEEKDAY(date)

In this syntax:

 date: This is the date value that you want to get the weekday from. The date can
be a DATE or DATETIME value.
The WEEKDAY() function returns an integer that represents from Monday to Sunday.
Also, it returns NULL if the date is NULL, invalid, or zero ( 0000-00-00).

MySQL WEEKDAY() examples

Let’s take some examples of using the WEEKDAY() function.


1) Simple WEEKDAY() function example
The following example uses the WEEKDAY() function to get the weekday index for the
date '2010-01-01':
SELECT
DAYNAME('2010-01-01'),
WEEKDAY('2010-01-01');

Output:

+-----------------------+-----------------------+
| DAYNAME('2010-01-01') | WEEKDAY('2010-01-01') |
+-----------------------+-----------------------+
| Friday | 4|
+-----------------------+-----------------------+
1 row in set (0.00 sec)

MySQL DAY() function

The DAY() function returns the day of the month for a specific date.
Here’s the syntax of the DAY() function:
DAY(date);
The DAY() function accepts a DATE or DATETIME value for which you want to get the day
of the month.
If the date is zero i.e.,'0000-00-00', the DAY() function returns 0. If the date is NULL,
the DAY() function returns NULL.
Note that DAY() function is the synonym of the DAYOFMONTH() function.

MySQL DAY() function examples

Let’s take some examples of using the DAY() function.


1) Simple DAY() function example
The following example uses the DAY() function to get the day of the month of the date
value 2010-01-15:
SELECT DAY('2010-01-15');

Output:

+-------------------+
| DAY('2010-01-15') |
+-------------------+
| 15 |
+-------------------+
1 row in set (0.00 sec)
MySQL DAYOFYEAR() function

The DAYOFYEAR() function allows you to get the day of the year for a date.
Here’s the syntax of the DAYOFYEAR() function:
DAYOFYEAR(date)

In this syntax:

 date: This is the date for which you want to determine the day of the year.

The function returns the day of the year (1 to 366) from the given date. It returns NULL if
the date is NULL.

MySQL DAYOFYEAR() function examples

Let’s take some examples of using the DAYOFYEAR() function.


1) Basic the DAYOFYEAR() function example
The following example uses the DAYOFYEAR() function to get the day of the year for the
date '2023-10-20':
SELECT DAYOFYEAR('2023-10-20')

Output:

+-------------------------+
| DAYOFYEAR('2023-10-20') |
+-------------------------+
| 293 |
+-------------------------+
1 row in set (0.00 sec)

DAYOFWEEK() function

The DAYOFWEEK() function allows you to get a weekday index of a date i.e., 1 for
Sunday, 2 for Monday, … 7 for Saturday.
Here’s the syntax of the DAYOFWEEK() function:
DAYOFWEEK(date)
The DAYOFWEEK function accepts a DATE or DATETIME value. It returns an integer that
ranges from 1 to 7 that represents Sunday to Saturday.
Note that DAYOFWEEK() function returns an index value based on the ODBC standard
where weekdays are indexed with values, with 1 representing Sunday, 2 representing
Monday, and so on.
If the date is NULL, zero ( 0000-00-00), or invalid, the DAYOFWEEK function returns NULL.

MySQL DAYOFWEEK() function examples

Let’s take some examples of using the DAYOFWEEK() function.


1) Simple DAYOFWEEK function example
The following example uses the DAYOFWEEK() function to return the weekday index
of December 1st, 2012:
SELECT
DAYNAME('2012-12-01'),
DAYOFWEEK('2012-12-01'); script)

Output:
+-----------------------+-------------------------+
| DAYNAME('2012-12-01') | DAYOFWEEK('2012-12-01') |
+-----------------------+-------------------------+
| Saturday | 7|
+-----------------------+-------------------------+
1 row in set (0.02 sec)

MySQL HOUR() function

The HOUR() function allows you to extract the hour component of a time value.
Here’s the basic syntax of the HOUR() function:
HOUR(time)

In this syntax:

 time: The time that you want to extract the hour component. The time value has
the data type is TIME.

The HOUR() function returns an integer that represents the hour component of the time.
If the time represents the time of the day, the HOUR() function returns a value between 0
and 23. But if the time value is larger, the HOUR() function can return values greater
than 23.
If the time is NULL, the HOUR() function returns NULL.

MySQL HOUR() function examples

Let’s take some examples of using the HOUR() function.


1) Simple HOUR() function example
The following example uses the HOUR() function to get the hour from the time ’10:45:20′:
SELECT HOUR('10:45:20');

Output:

+------------------+
| HOUR('10:45:20') |
+------------------+
| 10 |
+------------------+
1 row in set (0.01 sec)

MySQL MINUTE() function

The MINUTE() function allows you to extract the minute component of a time value.
Here’s the basic syntax of the MINUTE() function:
MINUTE(time)

In this syntax:

 time: The time that you want to extract the minute component. The time value
has the data type is TIME.
The MINUTE() function returns an integer that represents the minute component of the
time.
If the time represents the time of the day, the MINUTE() function returns a value between
0 and 59. But if the time value is larger, the MINUTE() function can return values greater
than 59.
If the time is NULL, the MINUTE() function returns NULL.

MySQL MINUTE() function examples

Let’s take some examples of using the MINUTE() function.


1) Simple MINUTE() function example
The following example uses the MINUTE() function to get the minute from the
time '10:45:20':
SELECT MINUTE('10:45:20');

Output:

+--------------------+
| MINUTE('10:45:20') |
+--------------------+
| 45 |
+--------------------+
1 row in set (0.00 sec)

MySQL SECOND() function

The SECOND() function allows you to extract the second component of a time value.

Here’s the basic syntax of the SECOND() function:

SECOND(time)

In this syntax:

 time: The time that you want to extract the second component. The time value
has the data type is TIME.

The SECOND() function returns an integer that represents the second component of the
time.

If the time represents the time of the day, the SECOND() function returns a value
between 0 and 59. But if the time value is larger, the SECOND() function can return
values greater than 59.

If the time is NULL, the SECOND() function returns NULL.

MySQL SECOND() function example

The following example uses the SECOND() function to get the second from the
time '10:45:20':

SELECT SECOND('10:45:20');
Output:

+--------------------+
| SECOND('10:45:20') |
+--------------------+
| 20 |
+--------------------+
1 row in set (0.00 sec)

MySQL LAST_DAY() function

The LAST_DAY() function takes a DATE or DATETIME value and returns the last day of the
month for the input date:
LAST_DAY(date);
The date argument must be a valid DATE or DATETIME value.
The LAST_DAY() function returns NULL if the date is zero ( 0000-00-00), invalid, or NULL.

MySQL LAST_DAY() function examples

Let’s take some examples of using the LAST_DAY() function.


1) MySQL LAST_DAY() simple example
The following example uses the LAST_DAY() function to return the last day of February
03, 2016.
SELECT LAST_DAY('2016-02-03');

Here is the output:

+------------------------+
| LAST_DAY('2016-02-03') |
+------------------------+
| 2016-02-29 |
+------------------------+
1 row in set (0.00 sec)

MySQL MONTHNAME() function

The MONTHNAME() function returns the name e of a month for a date.


Here’s the syntax of the MONTHNAME() function:
MONTHNAME(date)

In this syntax:

 date: This is the date on which you want to get the month’s name.

The MONTHNAME() function returns a string that represents the name of the month for
the given date.
If the date is NULL, the MONTHNAME() function returns NULL.

MySQL MONTHNAME() function example


Let’s take some examples of using the MONTHNAME() function.
1) Simple MONTHNAME() function example
The following example uses the MONTHNAME() function to get the month name of the
date '2023-10-16':
SELECT MONTHNAME('2023-10-16') Month;

Output:

+---------+
| Month |
+---------+
| October |
+---------+
1 row in set (0.00 sec)

You might also like