如何在 MySQL 中为日期添加天数?
如要为日期添加天数,你可以使用 MySQL 的 DATE_ADD() 函数。为日期添加天数的语法如下−
INSERT INTO yourTableName VALUES(DATE_ADD(now(),interval n day));
在上述语法中,你可以使用 curdate() 替换 now()。curdate() 只会存储日期,而 now() 会存储日期和时间。
下面是这两个函数的演示。为了理解上述语法,我们创建一个表。
mysql> create table addingDaysDemo −> ( −> yourDateTime datetime −> ); Query OK, 0 rows affected (1.09 sec)
现在在 insert 语句中同时使用这两个函数 now() 和 curdate(),并使用“间隔”来添加天数。为日期添加天数的查询如下−
mysql> insert into addingDaysDemo values(date_add(now(),interval 1 day)); Query OK, 1 row affected (0.14 sec) mysql> insert into addingDaysDemo values(date_add(now(),interval 4 day)); Query OK, 1 row affected (0.17 sec) mysql> insert into addingDaysDemo values(date_add(now(),interval 5 day)); Query OK, 1 row affected (0.14 sec) mysql> insert into addingDaysDemo values(date_add(now(),interval 7 day)); Query OK, 1 row affected (0.17 sec) mysql> insert into addingDaysDemo values(date_add(now(),interval 9 day)); Query OK, 1 row affected (0.15 sec) mysql> insert into addingDaysDemo values(date_add(curdate(),interval 1 day)); Query OK, 1 row affected (0.18 sec) mysql> insert into addingDaysDemo values(date_add(curdate(),interval 4 day)); Query OK, 1 row affected (0.16 sec) mysql> insert into addingDaysDemo values(date_add(curdate(),interval 5 day)); Query OK, 1 row affected (0.17 sec) mysql> insert into addingDaysDemo values(date_add(curdate(),interval 7 day)); Query OK, 1 row affected (0.12 sec) mysql> insert into addingDaysDemo values(date_add(curdate(),interval 9 day)); Query OK, 1 row affected (0.15 sec)
使用 select 语句显示表中的所有记录。查询如下−
mysql> select *from addingDaysDemo;
输出如下−
+---------------------+ | yourDateTime | +---------------------+ | 2018-12-14 15:36:57 | | 2018-12-17 15:37:06 | | 2018-12-18 15:37:12 | | 2018-12-20 15:37:17 | | 2018-12-22 15:37:21 | | 2018-12-14 00:00:00 | | 2018-12-17 00:00:00 | | 2018-12-18 00:00:00 | | 2018-12-20 00:00:00 | | 2018-12-22 00:00:00 | +---------------------+ 10 rows in set (0.00 sec)
广告