To find the first day of the previous and following months relative to a given date, n would be -1 and 1: : ADDDATE « Date Time « SQL / MySQL






To find the first day of the previous and following months relative to a given date, n would be -1 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_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             |
| 1987-03-05 | 1987-02-01            | 1987-04-01             |
| 1999-12-31 | 1999-11-01            | 2000-01-01             |
| 2000-06-04 | 2000-05-01            | 2000-07-01             |
+------------+-----------------------+------------------------+
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.Use the ADDDATE() function to add 10 hours and 20 minutes to the specified date/time value
2.The ADDDATE() function includes a second form: ADDDATE(, )
3.ADDDATE (date, INTERVAL n i) adds n times the interval i to the starting date date.
4.ADDDATE('2005-12-31', INTERVAL '3:30' HOUR_MINUTE) returns '2005-12-31 03:30:00'.
5.ADDDATE ('2005-12-31', INTERVAL 2 month)
6.Get the number, the date of birth, and the date that comes seven days after that date of birth.