簡體   English   中英

獲取從日期到月末PHP的秒數

[英]Get seconds from a date to end of month PHP

從sql數據庫表中提取訂閱日期,我們希望客戶在一年后的月末之前進行付款。 訂閱只是一個月內的某個日期。 一年后的部分很容易,找出那個月末的位置,並在幾秒鍾內將它添加到一年的部分給我帶來了問題。

日期存儲為unix接地零點的秒數。 如何查找從該值到該月末的秒數? 我已經嘗試使用miY將日期值轉換為實際日期

月底:

$expDate = date('m-i-Y',$row1["renewDate"]);

這有效。 我以字符串形式獲得該月的最后一天。 但如果我嘗試:

$endOfMonth = strtotime($expDate);

不起作用....

echo'ing $expDate以字符串形式顯示該月的最后一天。

echo'ing $endOfMonth什么都不返回......

感謝您對此的任何想法。

使用任意日期格式時, strtotime無法正常工作。 您有兩種選擇:

  1. 使用date_create_from_format來解析自定義日期格式。
  2. 將您的字符串轉換為自動理解strtotime Ymd格式。

例如:

$date = date('Y-m-t', $row1["renewDate"]);
$timestamp = strtotime($date);

PS正如評論中提到的,你應該使用t而不是i

你可以玩這樣的東西。 如果數據庫具有Epoch時間,則可以使用“@”符號將其轉換為日期。 您可以使用m / t / Y獲取該方式的訂閱日期,也可以獲得訂閱月份日期的結束日期。 您可以使用get Timestamp將其轉換回DT然后轉換為UNIX時間。 看起來它適用於時間= 1560961801。

$row1["renewDate"] = 1560961801;
$unixfromDB = $row1["renewDate"];

$date = new DateTime('@' .$unixfromDB); // your UNIX timestamp.     
$subdate =  $date->format( 'm/d/Y' ); // subscription date

$endmonth = $date->format( 'm/t/Y' ); // end of month date
$endmonth = DateTime::createFromFormat('m/d/Y', $endmonth);
$endmonth = $endmonth->getTimestamp();  // UNIX timestamp for end of month.

echo ($endmonth - $unixfromDB) / (60 * 60 *24);  // days to end of month

嘗試使用mktime()而不是strtotime()

<?
/* establish variables */
$now=time();    // epoch seconds right now
$expDate = date('m-t-Y', $row1["renewDate"]);   //note the switch to 't' as suggested by @ehymel
$eom = mktime($expDate);    // converts 'end of month' date into epoch seconds

/* results */
$secondsleft = $eom - $now;     // number of seconds until the end of the month
echo $secondsleft;  // return results
?>

不幸的是,mktime($ expDate)不起作用,至少使用CentOS6.9。 即使使用expdate變量,它仍然返回當前系統時間。

使用strtotime可識別的日期格式,Ymt,確實可以正常工作。 謝謝用戶1597430 ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM