【问题标题】:Trouble with PHP date() - remaining days in monthPHP date() 的问题 - 月中剩余的天数
【发布时间】:2016-12-14 17:34:59
【问题描述】:

我正在尝试从任何一天开始计算一个月内剩余的天数。我有以下代码:

<?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

我也尝试过使用 date('d', $timestamp),但它仍然返回 1,即使它应该是 14。为什么我今天得到 1?谢谢。

我的 PHP 版本是 5.4.45。

【问题讨论】:

  • 尝试使用$timestamp = time() 而不是$timestamp = date('Y-m-d')
  • 改用DateTime3v4l.org/bLOO7

标签: php date timestamp


【解决方案1】:

只需将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

【讨论】:

    【解决方案2】:

    使用 PHP 的 DateTime class 使这变得更简单:-

    $now = new \DateTime();
    $daysRemaining = (int)$now->format('t') - (int)$now->format('d');
    

    See it working.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      • 2021-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多