使用上个月 - PHP脚本

时间:2014-02-14 04:52:13

标签: php

以下是代码片段,它是更大规模的例程的一部分,虽然我需要帮助的是更改代码,因此它使用上个月或定义月份的能力。

当执行此操作时,它会根据当前月份(即二月份)向MySQL添加数据,但我需要让它在一月份添加数据(一次)。

任何帮助都会很棒。

$now = new DateTime('now');
$thisYear = $now->format("Y");
$thisMonth = $now->format('m');
$bookingsSql = str_replace('{check_in_year}', $thisYear, $bookingsSql);
$bookingsSql = str_replace('{check_in_month}', $thisMonth, $bookingsSql);
$bookingsSql = str_replace('{check_out_year}', $thisYear, $bookingsSql);
$bookingsSql = str_replace('{check_out_month}', $thisMonth, $bookingsSql);
$bookingsSql = str_replace('{close_date_year}', $thisYear, $bookingsSql);
$bookingsSql = str_replace('{close_date_month}', $thisMonth, $bookingsSql);

1 个答案:

答案 0 :(得分:0)

您可以在创建DateTime对象时指定“上个月”作为参数。

$myDate = new DateTime ("last month");
print "Date: {$myDate->format("d")}, month: {$myDate->format("m")}\n";
// Output: Date: 14, month: 01

或者,您也可以使用DateTime::sub()来更改日期。

$myToday = new DateTime ();
$lastmonth = $myToday->sub (new DateInterval ('P1M'));
print "Last month: {$lastmonth->format("m")}\n";
// Output: Last month: 01

如果您愿意,也可以定义自己的日期。请参阅the DateTime() manual