开发者

How to increment date with 1 (day/year) in PHP?

I have a date stored in an array:

$this->lines['uDate']

The format of the date is not fixed. I can be changed with this:

  define('DATETIME_FORMAT', 'y-m-d H:i');

How can I increment my uDate with a certain number of days or years?


My question is related to this one:

increment date by one month

However, in my case the date format in dynamic.

So, can I do this?

$time= $this->lines['uDate'];
$time = date(DATETIME_FORMAT, st开发者_StackOverflowrtotime("+1 day", $time));
$this->lines['uDate']= $time;


date_add()

and consider changes like:

define(DATETIME_FORMAT, 'y-m-d H:i');

$time = date(DATETIME_FORMAT, strtotime("+1 day", $time));


You can use some simple calculation to do it if you have the timestamp.

$date = strtotime($this->lines['uDate']); //assuming it's not a timestamp\
$date = $date + (60 * 60 * 24); //increase date by 1 day
echo  date('d-m-y', $date);
$date = $date + (60 * 60 * 24 * 365); //increase date by a year
echo  date('d-m-y', $date);

You can also use the mktime() method to do this : http://php.net/manual/en/function.mktime.php


function add_date($givendate,$day=0,$mth=0,$yr=0) 
{
      $cd = strtotime($givendate);
      $newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
    date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
    date('d',$cd)+$day, date('Y',$cd)+$yr));
      return $newdate;
}

I have found this in PHP help


another useful way, if you want an object rather than a string:

$date = DateTimeImmutable::createFromFormat('Y-m-d', '2022-01-05'); // just an exemplary date

$date = $date->add(date_interval_create_from_date_string('1 day')); // count up

notable difference:

date_add() changes the original object, while DateTimeImmutable::add() does not and simply returns the new object. Depending on the desired behavior, use one or the other.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜