MySQL date processing skills

Date and time data are very common and important data types in databases. MySQL provides a wealth of date processing functions that can help us perform various operations, formatting and calculations on date data. This article will give an in-depth introduction to the common skills of date processing in MySQL, so that you can manipulate date data more elegantly.

First, the basic operation of the date

Get the current date and time: Use the NOW() function to get the current date and time:

SELECT NOW();

Get the year, month, and day of a specified date:
Use the YEAR(), MONTH(), and DAY() functions to get the year, month, and day, respectively:

SELECT YEAR(date_column), MONTH(date_column), DAY(date_column) FROM table_name;

2. Date formatting

Use the DATE_FORMAT() function to format a date into a specific format:

SELECT DATE_FORMAT(date_column, '%Y-%m-%d') FROM table_name;

Commonly used date format placeholders:
%Y: four-digit year
%m: two-digit month
%d: two-
digit date %H: 24-hour hour
%i: minute
%s: second

3. Date Calculation

Add dates using the DATE_ADD() function:

SELECT DATE_ADD(date_column, INTERVAL 1 DAY) FROM table_name;

Subtract dates using the DATE_SUB() function:

SELECT DATE_SUB(date_column, INTERVAL 1 MONTH) FROM table_name;

4. Date comparison

Use the DATEDIFF() function to calculate date differences:

SELECT DATEDIFF('2023-07-15', '2023-07-01');

Use the DATE_ADD() function for date comparisons:

SELECT * FROM table_name WHERE date_column > DATE_ADD(NOW(), INTERVAL -7 DAY);

5. Processing timestamps

Convert date to timestamp:

Use the UNIX_TIMESTAMP() function to convert a date to a timestamp:

SELECT UNIX_TIMESTAMP(date_column) FROM table_name;

Convert timestamps to dates:
Use the FROM_UNIXTIME() function to convert timestamps to dates:

SELECT FROM_UNIXTIME(timestamp_column) FROM table_name;

In the MySQL database, the processing of dates is an essential part. Basic date operations, formatting, calculation and comparison skills allow you to handle date data more elegantly and perform more complex queries and statistics. By deeply understanding MySQL's date processing functions, you can manipulate dates more freely in database development and write efficient and accurate date-related codes. In practical applications, combining different date processing techniques can easily meet various complex business needs.

Guess you like

Origin blog.csdn.net/qq_35222232/article/details/132193184