【问题标题】:An error of type E_ERROR was caused in line 26 of the file Error message: Uncaught Exception: DateTime::__construct(): Failed to parse time string在文件的第 26 行导致了 E_ERROR 类型的错误错误消息:未捕获的异常:DateTime::__construct(): Failed to parse time string
【发布时间】:2021-10-18 17:01:06
【问题描述】:

在文件错误的第 26 行中导致了 E_ERROR 类型的错误 消息:未捕获异常:DateTime::__construct():解析失败 位置 0 ({) 处的时间字符串 ({field:launche_date_1623800874977}): 意外字符

function time_elapsed_string($datetime, $full = false) {
    $now = get_field('event_date', false, false);
    $now = new DateTime();
    
    $ago = new DateTime($datetime);
    

    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' old' : 'NA';
}

请帮帮我。

【问题讨论】:

标签: php


【解决方案1】:

问题:

  1. 仅仅依靠日期/时间库以任意日期字符串的格式猜测在任何语言中都是一个坏主意。在 PHP 中,您需要使用 DateTime::createFromFormat() 根据特定格式进行解析。
  2. 正如@digijay 所提到的,这不是一种可猜测的格式。
  3. 毫秒时间戳的问题在于 PHP 的 DateTime 库总是会消耗整个数字并将其解释为秒,无论您如何在模式中摆弄占位符。
  4. 即使是常规的 Unix 时间戳(以秒为单位)仍然不是 DateTime 构造函数的可猜测格式。

因此,无论哪种方式,您都需要在它进入您发布的函数之前对其进行预解析。

假设您已经从数据结构中找出时间戳:

$timestamp_ms = 1623800874977;
$timestamp = intdiv($timestamp_ms, 1000);

时间戳到日期时间的转换有两种方式:

$dt = DateTime::createFromFormat('U', $timestamp);
$dt = (new DateTime())->setTimestamp($timestamp);

现在我的偏好是修改您现有的函数以接受 DateTime 对象而不是任意字符串,以应对这种情况和其他“不可猜测”的边缘情况,在这种情况下,我们将完成这一天。但是,如果您有很多无法真正修改的周围代码,并且您真的想将其混杂在一起并传入一个正确“可猜测”的字符串:

$date_string = $dt->format('c');

其中c 是ISO8601 格式说明符,而ISO8601 是一种易于识别且不会被猜错的格式。例如:2021-06-15T23:47:54+00:00

【讨论】:

    猜你喜欢
    • 2016-07-09
    • 2018-08-18
    • 2014-03-17
    • 2012-05-06
    • 2012-04-25
    • 1970-01-01
    • 2016-02-27
    • 2015-01-04
    • 1970-01-01
    相关资源
    最近更新 更多