简体   繁体   中英

how do I subtract 24 hour from date time object in PHP

I have the following code:

  $now = date("Y-m-d H:m:s");
  $date = date("Y-m-d H:m:s", strtotime('-24 hours', $now));

However, now it gives me this error:

A non well formed numeric value encountered in...

why is this?

$date = (new \DateTime())->modify('-24 hours');

or

$date = (new \DateTime())->modify('-1 day');

(The latter takes into account this comment as it is a valid point.)

Should work fine for you here. See http://PHP.net/datetime

$date will be an instance of DateTime , a real DateTime object.

strtotime() expects a unix timestamp (which is number seconds since Jan 01 1970 )

$date = date("Y-m-d H:i:s", strtotime('-24 hours', time())); ////time() is default so you do not need to specify.

i would suggest using the datetime library though, since it's a more object oriented approach.

$date = new DateTime(); //date & time of right now. (Like time())
$date->sub(new DateInterval('P1D')); //subtract period of 1 day

The advantage of this is that you can reuse the DateInterval :

$date = new DateTime(); //date & time of right now. (Like time())
$oneDayPeriod = new DateInterval('P1D'); //period of 1 day
$date->sub($oneDayPeriod);
$date->sub($oneDayPeriod); //2 days are subtracted.
$date2 = new DateTime(); 
$date2->sub($oneDayPeriod); //can use the same period, multiple times.

Carbon (update 2020)

Most popular library for processing DateTimes in PHP is Carbon .

Here you would simply do:

$yesterday = Carbon::now()->subDay();

you can do this in many ways...

echo date('Y-m-d H:i:s',strtotime('-24 hours')); // "i" for minutes with leading zeros

OR

echo date('Y-m-d H:i:s',strtotime('last day')); // 24 hours (1 day)

Output

2013-07-17 10:07:29

Simplest way to sub or add time,

<?php
**#Subtract 24 hours**
$dtSub = new DateTime('- 24 hours');
var_dump($dtSub->format('Y-m-d H:m:s'));
**#Add 24 hours**
$dtAdd = new DateTime('24 hours');
var_dump($dtAdd->format('Y-m-d H:m:s'));die;
?>

This may be helpful for you:

//calculate like this
$date = date("Y-m-d H:m:s", (time()-(60*60*24)));

//check the date
echo $date;

这也应该有效

$date = date("Y-m-d H:m:s", strtotime('-24 hours'));
$now = date("Y-m-d H:i:s");
$date = date("Y-m-d H:i:s", strtotime('-24 hours', strtotime($now)));

Add "strtotime" before $now, and Ymd H:m:s replace with Ymd H:i:s

您可以简单地使用time()来获取当前时间戳。

$date = date("Y-m-d H:m:s", strtotime('-24 hours', time()));

In same code use strtotime() its working.

$now = date("Y-m-d H:i:s");
$date = date("Y-m-d H:i:s", strtotime('-2 hours', strtotime($now)));

all you have to do is to alter your code to be

$now = strtotime(date("Y-m-d H:m:s"));
$date = date("Y-m-d H:m:s", strtotime('-24 hours', $now));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM