Home >Database >SQL >How to use date functions in sql

How to use date functions in sql

下次还敢
下次还敢Original
2024-05-07 04:36:17523browse

Date functions are functions used to manipulate dates and times in SQL queries. Common date functions include getting the current date (CURDATE()), formatting the date (DATE_FORMAT()), adding or subtracting time intervals from the date (DATE_ADD(), DATE_SUB()), and extracting the time part (EXTRACT()) and converting strings to date values ​​(STR_TO_DATE()). These functions are commonly used to process date-related data, such as getting the current date, formatting dates to meet specific needs, calculating the difference between dates, etc.

How to use date functions in sql

Date functions in SQL

What are date functions?

The date function is a function that operates on dates and times in SQL queries. They can be used to obtain, format, compare, and modify date and time values.

Common date functions

The following are some commonly used date functions in SQL:

  • CURDATE():Return the current date.
  • NOW(): Returns the current date and time.
  • DATE_FORMAT(date, format): Format the date value into the specified format.
  • DATE_ADD(date, interval): Add or subtract the specified time interval from the date.
  • DATE_SUB(date, interval): Subtract the specified time interval from the date.
  • EXTRACT(part from date): Extract the specified time part (for example, year, month, day) from the date.
  • STR_TO_DATE(string, format): Convert a string to a date value.
  • TO_DATE(string, format): Convert a string to a date value, similar to STR_TO_DATE.

Example of using date functions

Get the current date:

<code class="sql">SELECT CURDATE();</code>

Format the date:

<code class="sql">SELECT DATE_FORMAT('2023-03-08', '%Y-%m-%d');</code>

Add time interval to date:

<code class="sql">SELECT DATE_ADD('2023-03-08', INTERVAL 1 DAY);</code>

Subtract time interval from date:

<code class="sql">SELECT DATE_SUB('2023-03-08', INTERVAL 1 WEEK);</code>

Extract the time part of the date:

<code class="sql">SELECT EXTRACT(MONTH FROM '2023-03-08');</code>

Convert the string to a date value:

<code class="sql">SELECT STR_TO_DATE('03/08/2023', '%m/%d/%Y');</code>

The above is the detailed content of How to use date functions in sql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn