2016-03-21 38 views
-1

當我運行下面的PHP代碼:PHP日期時間對象格式DMY錯誤

$this_year_start = strtotime(new DateTime("first day of this year")->format('d/m/Y')); 
$this_year_end = strtotime(new DateTime("last day of this year")->format('d/m/Y')); 

我收到以下錯誤:

PHP Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR) in /home/admin/data.php on line 164 

我想今年開始的UNIX時間今年結束。但是這似乎有一些問題格式,並將其轉換爲unix時間。

+0

替換'和'date_create'新Datetime',但我懷疑, 「今年的第一天」被接受爲論點。 – fusion3k

回答

1

strtotime()輸出一個Unix時間戳 - 所有你需要的是要轉換的字符串。

您可以使用strtotime()的日期文本格式,如「昨天」或日期,如「1991年3月15日」。

若想獲得最新的一年,你知道的開始和結束日期,這樣你就可以簡單地把在「簡01」和「12月31日」在strtotime()字符串:

$this_year_start = strtotime('Jan 01'); 
$this_year_end = strtotime('Dec 31'); 

這兩個值將輸出:

1451624400

1483160400

對於結束日期,如果你想要做的,明年前最後一秒,你可以添加一天吧,第二個少:

$this_year_end = strtotime("Dec 31") + (60 * 60 * 24) - 1; 
1

年份從1月1日00.00.00開始,12月31日結束23:59.59。

所以對於精度,因爲我們需要一個答案,時間戳(使用秒),你應該做這樣的事情太適用時間:

// mktime(hour, minute, second, month, day, year) 
$this_year_start = mktime(0, 0, 0, 1, 1, date('Y')); 
$this_year_end = mktime(23, 59, 59, 12, 31, date('Y')); 
-1

這工作

$s = new DateTime("first day of this year"); 
$l = new DateTime("last day of this year"); 

echo 'First Day = ' . $s->format('d/m/Y'). PHP_EOL; 
echo 'Last Day = ' . $l->format('d/m/Y'). PHP_EOL; 
echo 'First Timestamp = ' . $s->getTimestamp(). PHP_EOL; 
echo 'Last Timestamp = ' . $l->getTimestamp(). PHP_EOL; 

和輸出

First Day = 01/01/2016 
Last Day = 31/12/2016 
First Timestamp = 1451606400 
Last Timestamp = 1483142400 

當然,如果你想一起運行它,那麼這會產生你的時間戳,notic Ë利用()

$this_year_start = (new DateTime("first day of this year"))->getTimestamp(); 
$this_year_end = (new DateTime("last day of this year"))->getTimestamp(); 
+0

隨機驅動 - 下投票或有原因 – RiggsFolly

+0

我沒有downvote,但他想要時間戳,所以你應該用' - > getTimestamp()'替換' - > format(...)''。 –

+1

@CharlotteDunois Yea剛剛意識到,所以我添加了' - > getTimestamp()' – RiggsFolly

2
如果你想訪問你需要用這些括號中的新創建的對象的內聯,這樣

$this_year_start = strtotime((new DateTime("first day of this year"))->format('d/m/Y')); 
          ^         ^
          |          | 

然而,這不是在舊版本的選項PHP。安全的方式做到這一點,是創建對象,將其分配給一個變量,然後訪問從喜歡新創建的變量的方法:

$date = new DateTime("first day of this year"); 
$this_year_start = strtotime($date->format('d/m/Y'));