获取从日期到月底的秒数 PHP

Get seconds from a date to end of month PHP

从 sql 数据库中提取订阅日期 table 我们希望客户在一年后的月底之前付款。订阅只是一个月内的某个日期。一年后的部分很容易,弄清楚那个月的月底在哪里,然后以秒为单位将其添加到一年后的部分给我带来了问题。

日期存储为从 unix 零开始的秒数。如何找到从该值到该月底的秒数?我尝试使用 m-i-Y

将日期值转换为实际日期

月底:

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

这行得通。我以字符串形式获得该月的最后一天。但如果我尝试:

$endOfMonth = strtotime($expDate);

没用....

回显 $expDate 以字符串形式显示月份的最后一天。

回声 $endOfMonth returns 什么都没有...

感谢您对此的任何想法。

strtotime 不适用于任意日期格式。您有两个选择:

  1. 使用 date_create_from_format 解析自定义日期格式。
  2. 将您的字符串转换为 strtotime 可以理解的 Y-m-d 格式 自动。

例如:

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

P.S。如评论中所述,您应该使用 t 而不是 i.

你可以试试这样的东西。如果数据库有纪元时间,那么您可以使用“@”符号将其转换为日期。您可以通过这种方式获取订阅日期,也可以使用 m/t/Y 获取订阅月份的结束日期。您可以使用 get Timestamp 将其转换回 DT,然后再转换为 UNIX 时间。看起来它适用于 time = 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 可以识别的日期格式,Y-m-t,确实工作正常。感谢 user1597430...