当前位置:网站首页>[MySQL usage Script] catch all MySQL time and date types and related operation functions (3)
[MySQL usage Script] catch all MySQL time and date types and related operation functions (3)
2022-07-05 13:22:00 【TakingCoding4Granted】
List of articles
It is recommended to read the first two blog posts :
1. Realize the conversion between date and day or time and second
problem
You want to convert the date or time into more basic units , For example, convert dates to days , Convert time to seconds . Usually , This is very helpful for calculating the date or time .
Solution
The way of conversion depends on the type of value to be converted :
- Realize the conversion between time and seconds , Use
TIME_TO_SEC()as well asSEC_TO_TIME()function ; - Realize the conversion between date and days , Use
TO_DAYS()as well asFROM_DAYS()function ; - Time date + Conversion between time and seconds , Use
UNIX_TIMESTAMP()orFROM_UNIXTIME()function .
Discuss
In the following discussion , Introduced how to carry out several different dates ( Time ) And the day ( second ) Mutual conversion between .
Time and seconds switch
As mentioned above , have access to TIME_TO_SEC() as well as SEC_TO_TIME() function .
function TIME_TO_SEC() Convert a time value to the corresponding number of seconds , conversely , Then use the function SEC_TO_TIME() .
mysql> SELECT t1,
-> TIME_TO_SEC(t1) AS 'TIME to seconds',
-> SEC_TO_TIME(TIME_TO_SEC(t1)) AS 'TIME to seconds to TIME'
-> FROM time_val;
+----------+-----------------+-------------------------+
| t1 | TIME to seconds | TIME to seconds to TIME |
+----------+-----------------+-------------------------+
| 15:00:00 | 54000 | 15:00:00 |
| 05:01:30 | 18090 | 05:01:30 |
| 12:30:20 | 45020 | 12:30:20 |
+----------+-----------------+-------------------------+
3 rows in set (0.00 sec)
If you want to convert the time value to minutes , Hours or days , You need to perform the corresponding division operation :
mysql> SELECT t1,
-> TIME_TO_SEC(t1) AS 'seconds',
-> TIME_TO_SEC(t1)/60 AS 'minutes',
-> TIME_TO_SEC(t1)/(60*60) AS 'hours',
-> TIME_TO_SEC(t1)/(24*60*60) AS 'days'
-> FROM time_val;
+----------+---------+----------+---------+--------+
| t1 | seconds | minutes | hours | days |
+----------+---------+----------+---------+--------+
| 15:00:00 | 54000 | 900.0000 | 15.0000 | 0.6250 |
| 05:01:30 | 18090 | 301.5000 | 5.0250 | 0.2094 |
| 12:30:20 | 45020 | 750.3333 | 12.5056 | 0.5211 |
+----------+---------+----------+---------+--------+
3 rows in set (0.00 sec)
If you don't want to keep decimal places , Then you can use FLOOR() function .
If you are using functions TIME_TO_SEC() A date was passed in + Value of time format , Then this function will extract the time part , Then discard the date part . actually , This can also be regarded as from DATETIME or TIMESTAMP Another way to extract the time part . for example :
mysql> SELECT dt,
-> TIME_TO_SEC(dt) AS 'time part in seconds',
-> SEC_TO_TIME(TIME_TO_SEC(dt)) AS 'time part as TIME'
-> FROM datetime_val;
+---------------------+----------------------+-------------------+
| dt | time part in seconds | time part as TIME |
+---------------------+----------------------+-------------------+
| 1970-01-01 00:00:00 | 0 | 00:00:00 |
| 1999-12-31 09:00:00 | 32400 | 09:00:00 |
| 2000-06-04 15:45:30 | 56730 | 15:45:30 |
| 2017-03-16 12:30:15 | 45015 | 12:30:15 |
+---------------------+----------------------+-------------------+
4 rows in set (0.00 sec)
The date and day change with each other
As mentioned above , If you have a time value , But you want to convert it to days , You can use TO_DAYS() as well as FROM_DAYS() function .
mysql> SELECT d,
-> TO_DAYS(d) AS 'DATE to days',
-> FROM_DAYS(TO_DAYS(d)) AS 'DATE to days to DATE'
-> FROM date_val;
+------------+--------------+----------------------+
| d | DATE to days | DATE to days to DATE |
+------------+--------------+----------------------+
| 1864-02-28 | 680870 | 1864-02-28 |
| 1900-01-15 | 693975 | 1900-01-15 |
| 1999-12-31 | 730484 | 1999-12-31 |
| 2000-06-04 | 730640 | 2000-06-04 |
| 2017-03-16 | 736769 | 2017-03-16 |
+------------+--------------+----------------------+
5 rows in set (0.00 sec)
Similarly , If you are TO_DAYS() Function incoming date + Time value , Then this function will extract the date part , Then discard the time part . for example :
mysql> SELECT dt,
-> TO_DAYS(dt) AS 'date part in days',
-> FROM_DAYS(TO_DAYS(dt)) AS 'date part as DATE'
-> FROM datetime_val;
+---------------------+-------------------+-------------------+
| dt | date part in days | date part as DATE |
+---------------------+-------------------+-------------------+
| 1970-01-01 00:00:00 | 719528 | 1970-01-01 |
| 1999-12-31 09:00:00 | 730484 | 1999-12-31 |
| 2000-06-04 15:45:30 | 730640 | 2000-06-04 |
| 2017-03-16 12:30:15 | 736769 | 2017-03-16 |
+---------------------+-------------------+-------------------+
4 rows in set (0.00 sec)
date + Time and seconds switch
about DATETIME and TIMESTAMP Type value , If the values of these two types are TIMESTAMP Within the range of types , From 1970 Year to 2038 year , Then you can use UNIX_TIMESTAMP() and FROM_UNIXTIME() To realize the mutual conversion between the two and the number of seconds . for example :
mysql> SELECT dt,
-> UNIX_TIMESTAMP(dt) AS seconds,
-> FROM_UNIXTIME(UNIX_TIMESTAMP(dt)) AS timestamp
-> FROM datetime_val;
+---------------------+------------+---------------------+
| dt | seconds | timestamp |
+---------------------+------------+---------------------+
| 1970-01-01 00:00:00 | 0 | 1970-01-01 08:00:00 |
| 1999-12-31 09:00:00 | 946602000 | 1999-12-31 09:00:00 |
| 2000-06-04 15:45:30 | 960104730 | 2000-06-04 15:45:30 |
| 2017-03-16 12:30:15 | 1489638615 | 2017-03-16 12:30:15 |
+---------------------+------------+---------------------+
4 rows in set (0.00 sec)
function UNIX_TIMESTAMP() Can also be DATE The value of type is converted to seconds , By default, the time part of these dates is 00:00:00 :
mysql> SELECT
-> CURDATE(),
-> UNIX_TIMESTAMP(CURDATE()),
-> FROM_UNIXTIME(UNIX_TIMESTAMP(CURDATE()));
+------------+---------------------------+------------------------------------------+
| CURDATE() | UNIX_TIMESTAMP(CURDATE()) | FROM_UNIXTIME(UNIX_TIMESTAMP(CURDATE())) |
+------------+---------------------------+------------------------------------------+
| 2022-07-02 | 1656691200 | 2022-07-02 00:00:00 |
+------------+---------------------------+------------------------------------------+
1 row in set (0.00 sec)
2. Calculate the interval between dates or times
problem
You want to know the interval between two dates or times .
Solution
Want to calculate the interval between two dates or times , You can use special functions , You can also set the date first ( Time ) To the sky ( second ), Then calculate the interval between the two . As for which function to use , It mainly depends on whether the two values you want to calculate are date or time type .
Discuss
The following describes several methods used to calculate dates ( Time ) The way of spacing .
Date of use ( Time ) Function calculation interval
Want to calculate the number of days between two date values , have access to DATEDIFF() function :
mysql> SET @d1 = '2022-01-01', @d2 = '2021-12-01';
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT DATEDIFF(@d1, @d2) AS 'd1 - d2', DATEDIFF(@d2, @d1) AS 'd2 - d1';
+---------+---------+
| d1 - d2 | d2 - d1 |
+---------+---------+
| 31 | -31 |
+---------+---------+
1 row in set (0.00 sec)
function DATEDIFF() It also applies to two dates + Value of time type , But the time part will be ignored in the calculation . therefore , This function applies to two DATE ,DATETIME or TIMESTAMP Calculate the number of days between values of type .
Want to calculate the interval between two time values , have access to TIMEDIFF() function :
mysql> SET @t1 = '12:00:00', @t2 = '16:30:00';
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT TIMEDIFF(@t1, @t2) AS 't1 - t2', TIMEDIFF(@t2, @t1) AS 't2 - t1';
+------------------+-----------------+
| t1 - t2 | t2 - t1 |
+------------------+-----------------+
| -04:30:00.000000 | 04:30:00.000000 |
+------------------+-----------------+
1 row in set (0.00 sec)
function TIMEDIFF() It also applies to two dates + Value of time type .
The interval between two time values can be expressed as a TIME Type value , The latter can be further used HOUR() ,MINUTE() as well as SECOND() Function to split . for example :
mysql> SELECT t1, t2,
-> TIMEDIFF(t2, t1) AS 't2 - t1 as TIME',
-> IF(TIMEDIFF(t2, t1) >= 0,'+','-') AS sign,
-> HOUR(TIMEDIFF(t2, t1)) AS hour,
-> MINUTE(TIMEDIFF(t2, t1)) AS minute,
-> SECOND(TIMEDIFF(t2, t1)) AS second
-> FROM time_val;
+----------+----------+-----------------+------+------+--------+--------+
| t1 | t2 | t2 - t1 as TIME | sign | hour | minute | second |
+----------+----------+-----------------+------+------+--------+--------+
| 15:00:00 | 15:00:00 | 00:00:00 | + | 0 | 0 | 0 |
| 05:01:30 | 02:30:20 | -02:31:10 | - | 2 | 31 | 10 |
| 12:30:20 | 17:30:45 | 05:00:25 | + | 5 | 0 | 25 |
+----------+----------+-----------------+------+------+--------+--------+
3 rows in set (0.00 sec)
If you want to calculate two dates or two dates + Interval between time values , You can also use TIMESTAMPDIFF() function . This function is flexible , You can specify the desired interval unit . for example :
mysql> SET @dt1 = '1900-01-01 00:00:00', @dt2 = '1910-01-01 00:00:00';
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT
-> TIMESTAMPDIFF(MINUTE, @dt1, @dt2) AS minutes,
-> TIMESTAMPDIFF(HOUR, @dt1, @dt2) AS hours,
-> TIMESTAMPDIFF(DAY, @dt1, @dt2) AS days,
-> TIMESTAMPDIFF(WEEK, @dt1, @dt2) AS weeks,
-> TIMESTAMPDIFF(YEAR, @dt1, @dt2) AS years;
+---------+-------+------+-------+-------+
| minutes | hours | days | weeks | years |
+---------+-------+------+-------+-------+
| 5258880 | 87648 | 3652 | 521 | 10 |
+---------+-------+------+-------+-------+
1 row in set (0.00 sec)
actually , function TIMESTAMPDIFF() In addition to supporting the above spacing units , And support MICROSECOND ,MONTH ,QUARTER . Besides , function TIMESTAMP() It can be used to calculate a person's age easily .
For the function TIMESTAMPDIFF() , There are two points that need special attention :
- If the first date ( Time ) The value is greater than the second , Then the result will be negative , This sum
DATEDIFF()as well asTIMEDIFF()The function is just the opposite ; - Although the function
TIMESTAMPDIFF()The function name of containsTIMESTAMP, But the range of its parameters is not affectedTIMESTAMPLimit of type value range .
Calculate the interval in basic units
Calculate two dates ( Time ) Another way of spacing is to use, for example : Basic units including seconds and days :
- Put two dates ( Time ) Convert to days or seconds ;
- Use the above two converted values to calculate the interval ;
- Turn the calculation result in days as seconds back to the date or time .
According to the date or time you want to calculate the interval , You need to use different conversion functions :
- Using functions
TIME_TO_SEC()andSEC_TO_TIME()Switch between time and seconds ; - Using functions
TO_DAYS()andFROM_DAYS()Convert between dates and days ; - Using functions
UNIX_TIMESTAMP()andFROM_UNIXTIME()Date of conduct + The conversion between time and seconds .
Calculate the time interval in seconds
mysql> SELECT t1, t2,
-> TIME_TO_SEC(t2) - TIME_TO_SEC(t1) AS 't2 - t1 (in seconds)',
-> SEC_TO_TIME(TIME_TO_SEC(t2) - TIME_TO_SEC(t1)) AS 't2 - t1 (as TIME)'
-> FROM time_val;
+----------+----------+----------------------+-------------------+
| t1 | t2 | t2 - t1 (in seconds) | t2 - t1 (as TIME) |
+----------+----------+----------------------+-------------------+
| 15:00:00 | 15:00:00 | 0 | 00:00:00 |
| 05:01:30 | 02:30:20 | -9070 | -02:31:10 |
| 12:30:20 | 17:30:45 | 18025 | 05:00:25 |
+----------+----------+----------------------+-------------------+
3 rows in set (0.00 sec)
Calculate two dates or dates in basic units + Time interval
When you want to convert two dates into a common basic unit relative to the same given reference time point , Then calculate the interval between them , The value range of the date determines the available conversion units :
- For self 1970-01-01 00:00:00 UTC Later
DATE,DATETIMEorTIMESTAMPtype , You can first convert these types of values into seconds , To achieve an interval accuracy of seconds ; - For the starting time from the implementation of the Gregorian calendar, that is 1582 - 1970-01-01 00:00:00 UTC Date , You can first convert the date into seconds , To achieve interval accuracy to the level of days ;
- For earlier dates , First convert the date into basic unit , Then it is more difficult to calculate the interval . here , Need to use programming language API , Because use SQL Statements can be difficult or infeasible .
Want to calculate two dates or dates + The number of days between time values , You can use it first TO_DAYS() The function converts it to days , Then calculate the interval between them in days . If you want to get the interval between them in weeks , You can divide the result by seven :
mysql> SET @days = TO_DAYS('1884-01-01') - TO_DAYS('1883-06-05');
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @days AS days, @days/7 AS weeks;
+------+---------+
| days | weeks |
+------+---------+
| 210 | 30.0000 |
+------+---------+
1 row in set (0.00 sec)
It should be noted that , You cannot directly convert days into months or years in a similar way , Because the length of the two is different . If you want to achieve this effect , You need to use the above TIMESTAMPDIFF() function .
For between TIMESTAMP Within the scope of type , It's between 1970 to 2038 Date between years + Time value , You can use UNIX_TIMESTAMP() Function to implement two such dates + The time interval between time values is accurate to the second level . Want to get the interval expressed in other units , You can easily convert seconds into minutes , Hours , Days or weeks . for example :
mysql> SET @dt1 = '1984-01-01 09:00:00';
Query OK, 0 rows affected (0.00 sec)
mysql> SET @dt2 = @dt1 + INTERVAL 14 DAY;
Query OK, 0 rows affected (0.00 sec)
mysql> SET @interval = UNIX_TIMESTAMP(@dt2) - UNIX_TIMESTAMP(@dt1);
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @interval AS seconds,
-> FLOOR(@interval / 60) AS minutes,
-> FLOOR(@interval / (60 * 60)) AS hours,
-> FLOOR(@interval / (24 * 60 * 60)) AS days,
-> FLOOR(@interval / (7 * 24 * 60 * 60)) AS weeks;
+---------+---------+-------+------+-------+
| seconds | minutes | hours | days | weeks |
+---------+---------+-------+------+-------+
| 1209600 | 20160 | 336 | 14 | 2 |
+---------+---------+-------+------+-------+
1 row in set (0.00 sec)
about TIMESTAMP Types can represent values outside the range , Because it cannot be used like the above UNIX_TIMESTAMP() function , So calculate two dates + The calculation of the interval between time type values is a little more cumbersome :
- use first
TO_DAYS()Function calculates the number of days between the date parts of the two , And then multiplied by the 24 × 60 × 60 Get the number of seconds ; - Then use
TIME_TO_SEC()Function calculates the number of seconds between the two time parts .
mysql> SET @dt1 = '1800-02-14 07:30:00';
Query OK, 0 rows affected (0.00 sec)
mysql> SET @dt2 = '1800-02-17 06:30:00';
Query OK, 0 rows affected (0.00 sec)
mysql> SET @interval =
-> ((TO_DAYS(@dt2) - TO_DAYS(@dt1)) * 24*60*60)
-> + TIME_TO_SEC(@dt2) - TIME_TO_SEC(@dt1);
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @interval AS seconds, SEC_TO_TIME(@interval) AS TIME;
+---------+----------+
| seconds | TIME |
+---------+----------+
| 255600 | 71:00:00 |
+---------+----------+
1 row in set (0.00 sec)
3. Add dates or times
problem
You want to add dates or times . for example , You want to add a given number of seconds to a time value , Or you want to set a date three weeks from today .
Solution
Add date or time , You have the following options :
- Use special functions ;
- Use
+ INTERVALor- INTERVALThe operator ; - First convert the corresponding value to basic unit , Then add and sum .
It should be noted that , The specific applicable function or operator depends on the type of date or time value .
Discuss
Use special functions or operators to add dates or times
Want to add a time type value to another time type value or date + Time type value , have access to ADDTIME() function :
mysql> SELECT ADDTIME(@t1, @t2);
+-------------------+
| ADDTIME(@t1, @t2) |
+-------------------+
| 27:30:00 |
+-------------------+
1 row in set (0.00 sec)
mysql> SET @dt = '1984-03-01 12:00:00', @t = '12:00:00';
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT ADDTIME(@dt, @t);
+---------------------+
| ADDTIME(@dt, @t) |
+---------------------+
| 1984-03-02 00:00:00 |
+---------------------+
1 row in set (0.00 sec)
You want to add a time type value to another date type value or date + Time type value , have access to TIMESTAMP() function :
mysql> SET @d = '1984-03-01', @t = '15:30:00';
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT TIMESTAMP(@d, @t);
+----------------------------+
| TIMESTAMP(@d, @t) |
+----------------------------+
| 1984-03-01 15:30:00.000000 |
+----------------------------+
1 row in set (0.00 sec)
mysql> SET @dt = '1984-03-01 12:00:00', @t = '12:00:00';
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT TIMESTAMP(@dt, @t);
+----------------------------+
| TIMESTAMP(@dt, @t) |
+----------------------------+
| 1984-03-02 00:00:00.000000 |
+----------------------------+
1 row in set (0.00 sec)
MySQL It also provides DATE_ADD() and DATE_SUB() Two functions , These two functions can be used to add a time period to a date , Or subtract a time period from a date . Each function accepts a date or date + Value of time type d And a time period as a parameter , That is, the usage syntax of the function is as follows :
DATE_ADD(d, INTERVAL val unit)
DATE_SUB(d, INTERVAL val unit)
The operator + INTERVAL and - INTERVAL It can realize similar functions :
d + INTERVAL val unit
d - INTERVAL val unit
among _unit_ Is the unit of time interval , and val Is the number of time intervals . Common units are SECOND ,MINUTE ,HOUR ,DAY ,MONTH as well as YEAR .
- Get the date three days from today :
mysql> SELECT CURDATE(), DATE_ADD(CURDATE(), INTERVAL 3 DAY);
+------------+-------------------------------------+
| CURDATE() | DATE_ADD(CURDATE(), INTERVAL 3 DAY) |
+------------+-------------------------------------+
| 2022-07-03 | 2022-07-06 |
+------------+-------------------------------------+
1 row in set (0.00 sec)
- Get the date a week from today :
mysql> SELECT CURDATE(), DATE_SUB(CURDATE(), INTERVAL 1 WEEK);
+------------+--------------------------------------+
| CURDATE() | DATE_SUB(CURDATE(), INTERVAL 1 WEEK) |
+------------+--------------------------------------+
| 2022-07-03 | 2022-06-26 |
+------------+--------------------------------------+
1 row in set (0.00 sec)
- Get from now on 60 The date and time of the hour :
mysql> SELECT NOW(), DATE_ADD(NOW(), INTERVAL 60 HOUR);
+---------------------+-----------------------------------+
| NOW() | DATE_ADD(NOW(), INTERVAL 60 HOUR) |
+---------------------+-----------------------------------+
| 2022-07-03 00:27:09 | 2022-07-05 12:27:09 |
+---------------------+-----------------------------------+
1 row in set (0.00 sec)
- Get from now on 14.5 The date and time of the hour :
mysql> SELECT NOW(), DATE_ADD(NOW(), INTERVAL '14:30' HOUR_MINUTE);
+---------------------+-----------------------------------------------+
| NOW() | DATE_ADD(NOW(), INTERVAL '14:30' HOUR_MINUTE) |
+---------------------+-----------------------------------------------+
| 2022-07-03 00:28:47 | 2022-07-03 14:58:47 |
+---------------------+-----------------------------------------------+
1 row in set (0.00 sec)
- Get from now on 3 God 4 The date and time of the hour :
mysql> SELECT NOW(), DATE_ADD(NOW(), INTERVAL '3 4' DAY_HOUR);
+---------------------+------------------------------------------+
| NOW() | DATE_ADD(NOW(), INTERVAL '3 4' DAY_HOUR) |
+---------------------+------------------------------------------+
| 2022-07-03 00:30:14 | 2022-07-06 04:30:14 |
+---------------------+------------------------------------------+
1 row in set (0.00 sec)
actually , function DATE_ADD() and DATE_SUB() It is interchangeable , for example , The following two expressions are actually equivalent :
DATE_ADD(d, INTERVAL -3 MONTH)
DATE_SUB(d, INTERVAL 3 MONTH)
Similarly , In addition to using functions DATE_ADD() and DATE_SUB() , You can also use operators + INTERVAL and - INTERVAL To achieve the same function :
mysql> SELECT CURDATE(), CURDATE() + INTERVAL 1 YEAR;
+------------+-----------------------------+
| CURDATE() | CURDATE() + INTERVAL 1 YEAR |
+------------+-----------------------------+
| 2022-07-03 | 2023-07-03 |
+------------+-----------------------------+
1 row in set (0.00 sec)
mysql> SELECT NOW(), NOW() - INTERVAL '1 12' DAY_HOUR;
+---------------------+----------------------------------+
| NOW() | NOW() - INTERVAL '1 12' DAY_HOUR |
+---------------------+----------------------------------+
| 2022-07-03 00:36:58 | 2022-07-01 12:36:58 |
+---------------------+----------------------------------+
1 row in set (0.00 sec)
function TIMESTAMPADD() You can also add a time period to a date or date + The value of time , The syntax it uses is also similar to functions DATE_ADD() similar :
TIMESTAMPADD(unit,interval,d) = DATE_ADD(d,INTERVAL interval unit)
4. Calculate the first day of a month 、 Last day or days
problem
Give a date , You want to determine the date of the first or last day of the month in which the date is located , Or in that month n The date of the first or last day of the month after the month , And the total number of days in a month .
Solution
To get the date value of the first day of the month in which a date is located , You need to use date translation calculation . To get the date value of the last day of the month in which a date is located , You can use it directly LAST_DAY() function . To get the number of days in a month , You can get the date value of the last day of the month first , Then use it DAYOFMONTH() Function .
Discuss
occasionally , You may have a reference date , And you want to get a target date value , But there is no fixed relative relationship between the two . for example , The number of days from the current date to the first and last day of the month is not fixed .
To get the date of the first day of the month in which the given date value is located , You can move a given date forward by DAYOFMONTH() Less 1 Days of :
mysql> SELECT d, DATE_SUB(d, INTERVAL DAYOFMONTH(d) - 1 DAY) AS '1st of month'
-> FROM date_val;
+------------+--------------+
| d | 1st of month |
+------------+--------------+
| 1864-02-28 | 1864-02-01 |
| 1900-01-15 | 1900-01-01 |
| 1999-12-31 | 1999-12-01 |
| 2000-06-04 | 2000-06-01 |
| 2017-03-16 | 2017-03-01 |
+------------+--------------+
5 rows in set (0.00 sec)
More generally , If you want to get the distance from a given date n The date value of the first day of the month in which the date after the month is located , You can use the following SQL sentence :
DATE_ADD(DATE_SUB(d,INTERVAL DAYOFMONTH(d)-1 DAY),INTERVAL n MONTH)
for example , For a given date , In order to determine the date of the first day of the month before and after this date , You can use the following SQL sentence :
mysql> SELECT d,
-> DATE_ADD(DATE_SUB(d, INTERVAL DAYOFMONTH(d) - 1 DAY), INTERVAL -1 MONTH)
-> AS '1st of previous month',
-> DATE_ADD(DATE_SUB(d, INTERVAL DAYOFMONTH(d) - 1 DAY), INTERVAL 1 MONTH)
-> AS '1st of following month'
-> FROM date_val;
+------------+-----------------------+------------------------+
| d | 1st of previous month | 1st of following month |
+------------+-----------------------+------------------------+
| 1864-02-28 | 1864-01-01 | 1864-03-01 |
| 1900-01-15 | 1899-12-01 | 1900-02-01 |
| 1999-12-31 | 1999-11-01 | 2000-01-01 |
| 2000-06-04 | 2000-05-01 | 2000-07-01 |
| 2017-03-16 | 2017-02-01 | 2017-04-01 |
+------------+-----------------------+------------------------+
5 rows in set (0.00 sec)
It is relatively simple to get the date of the last day of the month in which a given date is located , Because you can use functions directly LAST_DAY() :
mysql> SELECT d, LAST_DAY(d) AS 'last of month'
-> FROM date_val;
+------------+---------------+
| d | last of month |
+------------+---------------+
| 1864-02-28 | 1864-02-29 |
| 1900-01-15 | 1900-01-31 |
| 1999-12-31 | 1999-12-31 |
| 2000-06-04 | 2000-06-30 |
| 2017-03-16 | 2017-03-31 |
+------------+---------------+
5 rows in set (0.00 sec)
Similarly , More generally , If you want to get the distance from a given date n The date value of the last day of the month in which the date after months is located , You can use the following SQL sentence :
LAST_DAY(DATE_ADD(d, INTERVAL n MONTH))
for example , For a given date , You want to get the date of the last day of the month relative to the date one month ago and one month later , You can use the following SQL sentence :
mysql> SELECT d,
-> LAST_DAY(DATE_ADD(d, INTERVAL -1 MONTH))
-> AS 'last of previous month',
-> LAST_DAY(DATE_ADD(d, INTERVAL 1 MONTH))
-> AS 'last of following month'
-> FROM date_val;
+------------+------------------------+-------------------------+
| d | last of previous month | last of following month |
+------------+------------------------+-------------------------+
| 1864-02-28 | 1864-01-31 | 1864-03-31 |
| 1900-01-15 | 1899-12-31 | 1900-02-28 |
| 1999-12-31 | 1999-11-30 | 2000-01-31 |
| 2000-06-04 | 2000-05-31 | 2000-07-31 |
| 2017-03-16 | 2017-02-28 | 2017-04-30 |
+------------+------------------------+-------------------------+
5 rows in set (0.00 sec)
To get the number of days in a month , You can use it first LAST_DAY() function , And then use DAYOFMONTH() function :
mysql> SELECT d, DAYOFMONTH(LAST_DAY(d)) AS 'days in month' FROM date_val;
+------------+---------------+
| d | days in month |
+------------+---------------+
| 1864-02-28 | 29 |
| 1900-01-15 | 31 |
| 1999-12-31 | 31 |
| 2000-06-04 | 30 |
| 2017-03-16 | 31 |
+------------+---------------+
5 rows in set (0.00 sec)
5. Find the week name of a date
problem
You want to know the name of a given day .
Solution
Use DAYNAME() function .
Discuss
Want to know the week name corresponding to a given date , have access to DAYNAME() function :
mysql> SELECT CURDATE(), DAYNAME(CURDATE());
+------------+--------------------+
| CURDATE() | DAYNAME(CURDATE()) |
+------------+--------------------+
| 2022-07-03 | Sunday |
+------------+--------------------+
1 row in set (0.00 sec)
DAYNAME() Functions are usually used in conjunction with other date related operations . for example , Want to determine the Sunday name of the first day of a month , You can combine functions DAYOFMONTH() :
mysql> SET @d = CURDATE();
Query OK, 0 rows affected (0.00 sec)
mysql> SET @first = DATE_SUB(@d, INTERVAL DAYOFMONTH(@d) - 1 DAY);
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @d AS 'starting date',
-> @first AS '1st of month date',
-> DAYNAME(@first) AS '1st of month day';
+---------------+-------------------+------------------+
| starting date | 1st of month date | 1st of month day |
+---------------+-------------------+------------------+
| 2022-07-03 | 2022-07-01 | Friday |
+---------------+-------------------+------------------+
1 row in set (0.00 sec)
6. Find the date of any working day in a week
problem
You need to calculate the date corresponding to a working day in the week of a given date . Suppose you want to know and 2014-07-09 The date corresponding to Tuesday in the same week .
Solution
See the following discussion .
Discuss
Given the date 2014-07-09 , You want to know the date corresponding to Tuesday in the same week , Then you need to know 2014-07-09 This date corresponds to the number of weeks . for example , If 2014-07-09 On Monday , Then the date corresponding to the Tuesday of the same week as the date is the date shifted backward by one day , namely 2014-07-10 ; If 2014-07-09 Corresponding to Wednesday , Then the date corresponding to the Tuesday of the same week as the date is the date shifted forward by one day , namely 2014-07-08 .
For the above needs ,MySQL Two useful functions are provided . function DAYOFWEEK() Regard Sunday as the first day of the week , Saturday is regarded as the last day of the week , And corresponding numbers from Sunday to Saturday 1 1 1 To 7 7 7 ; function WEEKDAY() Think of Monday as the first day of the week , And corresponding numbers from Monday to Sunday 0 0 0 To 6 6 6 .
With the above function , Then we can solve the above problems according to this idea , namely :
- First , Move the given date forward
DAYOFWEEK()God , This step will get a date , And the date is always the Saturday of the week before the given date ; - next , Will be the first 1 1 1 Move the date obtained in step backward one day to get the date of Sunday , Shift back two days to get the date of Monday , By analogy .
The above steps correspond to SQL The statement is as follows :
DATE_ADD(DATE_SUB(d, INTERVAL DAYOFWEEK(d) DAY), INTERVAL n DAY)
among d Represents a given date , n n n The range of theta is zero 1 1 1 To 7 7 7, You can get and date respectively d The corresponding date from Sunday to Saturday in the same week . actually , The above expression can be further simplified as follows :
in the light of date_val The records in the table , You can get the Sunday and Saturday of the same week as the date in it ( Here Sunday is the first day of the week , The last day of Saturday ) The corresponding dates are as follows :
mysql> SELECT d, DAYNAME(d) AS day,
-> DATE_ADD(d, INTERVAL 1 - DAYOFWEEK(d) DAY) AS Sunday,
-> DATE_ADD(d, INTERVAL 7 - DAYOFWEEK(d) DAY) AS Saturday
-> FROM date_val;
+------------+----------+------------+------------+
| d | day | Sunday | Saturday |
+------------+----------+------------+------------+
| 1864-02-28 | Sunday | 1864-02-28 | 1864-03-05 |
| 1900-01-15 | Monday | 1900-01-14 | 1900-01-20 |
| 1999-12-31 | Friday | 1999-12-26 | 2000-01-01 |
| 2000-06-04 | Sunday | 2000-06-04 | 2000-06-10 |
| 2017-03-16 | Thursday | 2017-03-12 | 2017-03-18 |
+------------+----------+------------+------------+
5 rows in set (0.00 sec)
边栏推荐
猜你喜欢

uni-app开发语音识别app,讲究的就是简单快速。

Simple page request and parsing cases

Natural language processing series (I) introduction overview

Write macro with word

CAN和CAN FD

C object storage
![[notes of in-depth study paper]transbtsv2: wider instead of deep transformer for medical image segmentation](/img/70/6de0346df8527af6c88db1ff89947b.png)
[notes of in-depth study paper]transbtsv2: wider instead of deep transformer for medical image segmentation
![[深度学习论文笔记]使用多模态MR成像分割脑肿瘤的HNF-Netv2](/img/52/5e85743b1817de96a52e02b92fd08c.png)
[深度学习论文笔记]使用多模态MR成像分割脑肿瘤的HNF-Netv2

Shu tianmeng map × Weiyan technology - Dream map database circle of friends + 1

Principle and performance analysis of lepton lossless compression
随机推荐
Flutter draws animation effects of wave movement, curves and line graphs
Flutter 绘制波浪移动动画效果,曲线和折线图
今年上半年,通信行业发生了哪些事?
国际自动机工程师学会(SAE International)战略投资几何伙伴
Asemi rectifier bridge hd06 parameters, hd06 pictures, hd06 applications
初次使用腾讯云,解决只能使用webshell连接,不能使用ssh连接。
量价虽降,商业银行结构性存款为何受上市公司所偏爱?
AVC1与H264的区别
Rocky basic command 3
Fragmented knowledge management tool memos
Rocky基础知识1
使用Dom4j解析XML
leetcode:221. Maximum square [essence of DP state transition]
A detailed explanation of ASCII code, Unicode and UTF-8
碎片化知识管理工具Memos
Detailed explanation of navigation component of openharmony application development
时钟周期
MySQL splits strings for conditional queries
Word document injection (tracking word documents) incomplete
Sorry, we can't open xxxxx Docx, because there is a problem with the content (repackaging problem)