PHP subtract 1 month from date formated with date

2019-02-21 08:43发布

I'm trying to subtract 1 month from a date.

$today = date('m-Y');

This gives: 08-2016

How can I subtract a month to get 07-2016?

4条回答
霸刀☆藐视天下
2楼-- · 2019-02-21 09:07

Depending on your PHP version you can use DateTime object (introduced in PHP 5.2 if I remember correctly):

<?php
$today = new DateTime(); // This will create a DateTime object with the current date
$today->modify('-1 month');

You can pass another date to the constructor, it does not have to be the current date. More information: http://php.net/manual/en/datetime.modify.php

查看更多
beautiful°
3楼-- · 2019-02-21 09:09

Try this,

$today = date('m-Y');
$newdate = date('m-Y', strtotime('-1 months', strtotime($today))); 
echo $newdate;
查看更多
The star\"
4楼-- · 2019-02-21 09:10
 <?php 
  echo $newdate = date("m-Y", strtotime("-1 months"));

output

07-2016
查看更多
Animai°情兽
5楼-- · 2019-02-21 09:19

Warning! The above-mentioned examples won't work if call them at the end of a month.

<?php
$now = mktime(0, 0, 0, 10, 31, 2017);
echo date("m-Y", $now)."\n";
echo date("m-Y", strtotime("-1 months", $now))."\n";

will output:

10-2017
10-2017

The following example will produce the same result:

$date = new DateTime('2017-10-31 00:00:00');
echo $date->format('m-Y')."\n";
$date->modify('-1 month');
echo $date->format('m-Y')."\n";

Plenty of ways how to solve the issue can be found in another thread: PHP DateTime::modify adding and subtracting months

查看更多
登录 后发表回答