如何从今天的日期获取下个月日期并将其插入我的数据库?

2022-08-30 13:00:11

我的 db 中有两列:和 ,它们都是类型。我的代码正在更新日期,如下所示:start_dateend_dateDATE

$today_date = date("Y-m-d");
$end_date = date("Y-m-d"); // date +1 month ??

$sql1 = "UPDATE `users` SET `start_date` = '".$today_date."', `end_date` = '".$end_date."'  WHERE `users`.`id` ='".$id."' LIMIT 1 ;";

使等于+一个月的最佳方法是什么?例如,2000-10-01 将变为 2000-11-01。$end_date$start_date


答案 1

您可以使用 PHP 的 strtotime() 函数:

// One month from today
$date = date('Y-m-d', strtotime('+1 month'));

// One month from a specific date
$date = date('Y-m-d', strtotime('+1 month', strtotime('2015-01-01')));

请注意,这并不总是直观地计算出来。它似乎总是将当前月份存在的天数相加。+1 month

Current Date  | +1 month
-----------------------------------------------------
2015-01-01    | 2015-02-01   (+31 days)
2015-01-15    | 2015-02-15   (+31 days)
2015-01-30    | 2015-03-02   (+31 days, skips Feb)
2015-01-31    | 2015-03-03   (+31 days, skips Feb)
2015-02-15    | 2015-03-15   (+28 days)
2015-03-31    | 2015-05-01   (+31 days, skips April)
2015-12-31    | 2016-01-31   (+31 days)

您可以使用的其他一些日期/时间间隔:

$date = date('Y-m-d'); // Initial date string to use in calculation

$date = date('Y-m-d', strtotime('+1 day', strtotime($date)));
$date = date('Y-m-d', strtotime('+1 week', strtotime($date)));
$date = date('Y-m-d', strtotime('+2 week', strtotime($date)));
$date = date('Y-m-d', strtotime('+1 month', strtotime($date)));
$date = date('Y-m-d', strtotime('+30 days', strtotime($date)));

答案 2

接受的答案仅在您想要31天后才有效。这意味着如果你使用的日期“2013-05-31”,你预计不会在六月,这不是我想要的。

如果你想有下个月,我建议你使用当前的年份和月份,但继续使用第一个月。

$date = date("Y-m-01");
$newdate = strtotime ( '+1 month' , strtotime ( $date ) ) ;

这样,您将能够获得下个月的月份和年份,而不会跳过一个月。


推荐