Calculate the last day of the month for the previous, current, and following months relative to a given date, : DATE_SUB « Date Time « SQL / MySQL






Calculate the last day of the month for the previous, current, and following months relative to a given date,

     
n would be -1, 0, and 1
mysql>
mysql> CREATE TABLE date_val
    -> (
    ->  d       DATE
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql>
mysql> INSERT INTO date_val (d) VALUES('1864-02-28');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO date_val (d) VALUES('1900-01-15');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO date_val (d) VALUES('1987-03-05');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO date_val (d) VALUES('1999-12-31');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO date_val (d) VALUES('2000-06-04');
Query OK, 1 row affected (0.00 sec)

mysql>
mysql>
mysql> SELECT d,
    -> DATE_SUB(
    -> DATE_ADD(DATE_SUB(d,INTERVAL DAYOFMONTH(d)-1 DAY),INTERVAL 0 MONTH),
    -> INTERVAL 1 DAY)
    -> AS 'last, prev. month',
    -> DATE_SUB(
    -> DATE_ADD(DATE_SUB(d,INTERVAL DAYOFMONTH(d)-1 DAY),INTERVAL 1 MONTH),
    -> INTERVAL 1 DAY)
    -> AS 'last, this month',
    -> DATE_SUB(
    -> DATE_ADD(DATE_SUB(d,INTERVAL DAYOFMONTH(d)-1 DAY),INTERVAL 2 MONTH),
    -> INTERVAL 1 DAY)
    -> AS 'last, following month'
    -> FROM date_val;
+------------+-------------------+------------------+-----------------------+
| d          | last, prev. month | last, this month | last, following month |
+------------+-------------------+------------------+-----------------------+
| 1864-02-28 | 1864-01-31        | 1864-02-29       | 1864-03-31            |
| 1900-01-15 | 1899-12-31        | 1900-01-31       | 1900-02-28            |
| 1987-03-05 | 1987-02-28        | 1987-03-31       | 1987-04-30            |
| 1999-12-31 | 1999-11-30        | 1999-12-31       | 2000-01-31            |
| 2000-06-04 | 2000-05-31        | 2000-06-30       | 2000-07-31            |
+------------+-------------------+------------------+-----------------------+
5 rows in set (0.00 sec)

mysql>
mysql> drop table date_val;
Query OK, 0 rows affected (0.00 sec)

   
    
    
    
    
  








Related examples in the same category

1.Find the date a week ago
2.Calculated dates are useful for range testing
3.Finding First and Last Days of Months
4.Finding the Length of a Month
5.The last day of the previous month is a special case for which the general expression can be simplified quite