1

Below is a snippet of code that is part of a much bigger routine, although all I need assistance with is changing the code so it is uses the prior month, or the ability to define the month.

When this executes it adds data to MySQL based the current month, i.e. February but I need to have it also add data (once) for January.

Any help would be great.

$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 Answers1

0

You can specify "last month" as your argument when creating your DateTime object.

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

Alternatively, you can also use DateTime::sub() to alter the date you have.

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

You can also define your own date if you like. See the DateTime() manual.

Sutandiono
  • 1,748
  • 1
  • 12
  • 21
  • So if I change: $now = new DateTime('now'); to $now = new DateTime('last month'); the records will be created using January? – user3308857 Feb 14 '14 at 14:43
  • @user3308857 As the argument `last month` suggested, the `DateTime` object will be created using the month before current. If you run the script in February, then your records will start in January. If you run the script in August, your records will start in July. – Sutandiono Feb 17 '14 at 01:44