2016-12-14 20 views
0

我想從任何一天計算一個月內的剩餘天數。我有以下代碼:PHP日期問題() - 剩餘的月份日期

<?php 
date_default_timezone_set("UTC"); 
echo $timestamp = date('Y-m-d'); 
echo " - "; 
echo $daysInMonth = (int)date('t', $timestamp); 
echo " - "; 
echo $thisDayInMonth = (int)date('j', $timestamp); 
echo " - "; 
echo $daysRemaining = $daysInMonth - $thisDayInMonth; 
?> 

的輸出是: 2016年12月14日 - 31 - 1 - 30

我也曾嘗試與日期( 'd',$時間戳),但它仍然返回1,即使它應該是14.爲什麼我現在得到1?謝謝。

我的PHP版本是5.4.45。

+0

嘗試使用'DateTime'而不是'$ timestamp = time()'而不是'$ timestamp = date('Y-m-d')' –

+0

。 https://3v4l.org/bLOO7 –

回答

2

只需將strtotime添加到時間戳變量,因爲日期函數需要第二個參數作爲整數值。但是當你提供格式化日期時,它被認爲是字符串。

date_default_timezone_set("UTC"); 
echo $timestamp = date('Y-m-d'); 
echo " - "; 
echo $daysInMonth = (int)date('t', strtotime($timestamp)); 
echo " - "; 
echo $thisDayInMonth = (int)date('j', strtotime($timestamp)); 
echo " - "; 
echo $daysRemaining = $daysInMonth - $thisDayInMonth; 

輸出:

2016-12-14 - 31 - 14 - 17