2014-10-10 42 views
-1

我正在訪問網站上工作,付費會員將獲得到達網站的確切時間爲3個月訪問期間。因此問題是如何計算確切的3個月的日期。使用日期對象來計算日期期間的最準確方法

即一些月份是28天,另一些是31天;正常年份是365年,但是農曆年是 354天。

我正在考慮將日期轉換爲UNIX時間戳,然後以秒爲單位計算3個月。但我不確定這是否是最有效和最準確的方法。

下面是我的建議,我真的很感謝它的一些建議;

時間戳時鐘啓動時

$UNIXtimeStampNow = new \DateTime("now"))->format('U') 

計算從日起三個月:

$numberDaysInMonth = 30.41 = 365/ 12 //number of days in months 

    $numberSecondsInDay = 86400; //number seconds in a day 

$secondsIn3Months = ($numberDaysInMonth * $numberSecondsInDay) * 3 //number seconds in 3 months 

    new \DateTime("$secondsIn3Months"); //convert back to date object 

就像我說的,這是我想出的最好的,但我懷疑它不準確。

真的很合適,這裏有些建議

+0

這不是最有效的方法,最有效的方法是使用)與DateInterval日期時間的方法,如加(,尤其是當你正在做的大假設有86400秒每一天 – 2014-10-10 10:23:29

+1

'陰曆年是354天,它如何與你的任務相聯繫? – 2014-10-10 10:24:53

+0

爲什麼不添加相對日期 – Ghost 2014-10-10 10:26:52

回答

1

正如我在我的評論說,剛使用DateTime對象的add()方法有DateInterval

$d = new \DateTime("now"); 
$d->add(new \DateInterval('P3M')); 
echo $d->format('Y-m-d H:i:s'); 
+0

hi標記中工作。看起來不錯;但只是很快的問題。 'P3M'i'假設它的3個月,但我沒有看過這種格式。在哪裏可以獲得這些優惠活動呢?這個計算方法在某些月份有28天,31天和30天時也是準確的。 – 2014-10-10 10:47:37

+0

如果你閱讀[DateInterval構造函數](http://uk1.php.net/manual/en/dateinterval.construct.php)的PHP文檔,你會得到一個'P3M'的解釋,它是基於[ISO 8601規範](http://en.wikipedia.org/wiki/ISO_8601#Durations)持續時間 – 2014-10-10 10:53:38

+0

是的,DateTime可以處理您每個月的不同天數,只要它可以...潛在問題如果你的開始日期是11月30日,當你沒有說明你期望的結果是在該日期添加3個月 – 2014-10-10 10:56:32

0

轉換我的評論到的答案...

您可以使用PHP的內置函數strtotime實現這一目標。此功能Parse about any English textual datetime description into a Unix timestamp

所以,如果你已經使用UNIX時間戳工作,你可以做到這一點,從現在得到3個月,在Unix時間戳表示:

$three_months_from_now = strtotime("+3 month"); 

如果要輸出的值,它看起來會是像這樣:

echo date('d/m/Y H:i:s a', strtotime("+3 month")); 
// outputs: 10/01/2015 11:32:42 am 

注意,這是顯着不同的,如果您自己手動進行計算;即

<?php 

$now = time(); 
$one_hour = 3600; // seconds 
$one_day = $one_hour * 24; 
$one_month = 30 * $one_day; 
$three_months = 3 * $one_month; 

echo date('d/m/Y H:i:s a', $now + $three_months); 

// outputs: 08/01/2015 10:34:24 am 

?> 
+0

嗨Ltheesan。非常感謝您的快速回復。我的問題是,如何在28天,31天和30天的月份之間分散投資。這個時間(「+ 3個月」)每次都準確無誤。另外,我不需要在時間戳上工作。我可以在日期對象 – 2014-10-10 10:41:17

0

PHP 5的DateTime class是相當穩定的,使用 時,相應帶來準確的結果。在使用DateTime類時,建議您始終設置TimeZone 以達到時差精度目的。

//the string parameter, "now" gets us time stamp of current time 
/*We are setting our TimeZone by using DateTime class 
Constructor*/ 
$first = new DateTime("now",new DateTimeZone('America/New_York')); 

// 3 months from now and again setting the TimeZone 
$second = new DateTime("+ 3 months",new DateTimeZone('America/New_York')); 

$diff = $second->diff($first); 

echo "The two dates have $diff->m months and $diff->days days between them."; 

output: The two dates have 3 months and 92 days between them.