2013-07-18 115 views
21

我有以下代碼:我怎麼減去日期時間對象24小時PHP

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

不過,現在它給了我這個錯誤:

A non well formed numeric value encountered in... 

這是爲什麼?

+3

參見手冊 - 'strtotime'預計時間戳作爲第二值。 (在你的例子中,你可以完全忽略它) –

+2

你可能想要考慮節省時間的邊界:你真的想要從上午10點到上午11點(或上午9點?)開關。 –

+1

......沒有其他人發現'm'是我通常坐在時間部分的地方嗎?每一個答案副本粘貼這個疏忽。哈。 – mickmackusa

回答

25

strtotime()預計Unix時間戳(這是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. 

我將使用日期時間庫的建議,雖然,因爲它是一個更面向對象的方法。

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

這樣做的好處是,你可以重複使用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. 
36
$date = (new \DateTime())->modify('-24 hours'); 

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

(後者考慮到this comment,因爲它是一個有效點)

應該在這裏適合你。請參閱http://PHP.net/datetime

$ date將是一個實際的DateTime對象DateTime的實例。

+0

此答案就地修改原始DateTime對象。 – thedarklord47

+1

是的,這就是\ DateTime的工作方式。如果這對你沒有好處,請改用\ DateTimeImmutable。 – vascowhite

+0

啊謝謝!不知道DateTimeImmutable是一件事情。 – thedarklord47

1

這應該工作,太

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

這可能對你有所幫助:

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

//check the date 
echo $date; 
+0

Downvoted for unreliability:http://sandbox.onlinephpfunctions.com/code/729ae5a21769fdc06a5c340457d5793f28c04642 – mickmackusa

1

您可以簡單地使用time()獲得當前的時間戳。

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

你可以在許多方面做到這一點...

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) 

輸出

2013-07-17 10:07:29 
0

所有你需要做的是改變你的代碼是

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

添加 「的strtotime」 之前$現在, 和YMD H:M:S替換YMD H:我:■