【问题标题】:Failed to parse time string in PHP无法在 PHP 中解析时间字符串
【发布时间】:2016-03-11 09:44:04
【问题描述】:

我需要根据从表单接收到的值创建一个 DateTime。问题是该值像字符串一样被接收:“2016-10-10T08:29:06.959Z”,我需要像2016-10-10T08:29:06.959Z 一样接收不带引号,因为如果我收到带引号的消息,我会遇到下一个错误:

DateTime::__construct():在位置 0 (") 解析时间字符串 ("2016-10-14T22:00:00.000Z") 失败:意外字符

当我尝试将值转换为 DateTime 时:

$fechaHasta = new DateTime($params["fechaHasta"]);

如果我尝试使用:

$fecha2 = DateTime::createFromFormat("d-m-Y H:i:s", $data["fechaHasta"]);

我在 $fecha2 中有一个空对象。

我发送数据的形式是:

<form id = "formSearch" class = "menu-table" method = "post" action = "<?php echo $this->basePath('/privado/actividades-planificadas/pai/exportdatatoexcel'); ?>">
    <input type = "hidden" name = "codigoPPM" value = "{{searchForm.codigoPPM}}" />
    <input type = "hidden" name = "fechaDesde" value = {{searchForm.dt1}} />
    <input type = "hidden" name = "fechaHasta" value = {{searchForm.dt2}} />
    <input type = "hidden" name = "estado" value = "{{searchForm.estadoSelected.id}}" />
    <button type = "submit">
        Exportar datos a Excel&nbsp;&nbsp;&nbsp;<img title = "Exportar tabla a Excel" src = "/img/logo-excel.png" />
    </button>
</form> 

所以,我必须做些什么来发送不带引号的值或转换在 DateTime 中收到的值。

【问题讨论】:

  • 你试过去掉引号吗?
  • 如何删除引号或不带引号发送?

标签: php datetime


【解决方案1】:
$date = '"2016-10-14T22:00:00.000Z"';
=> ""2016-10-14T22:00:00.000Z""

$fechaHasta = new DateTime($date);
Exception with message 'DateTime::__construct(): Failed to parse time string ("2016-10-14T22:00:00.000Z") at position 0 ("): Unexpected character'

$fechaHasta = new DateTime(trim($date, '"')); /* « notice the trim */
=> DateTime {#174
     +"date": "2016-10-14 22:00:00.000000",
     +"timezone_type": 2,
     +"timezone": "Z",
   }

所以你只需将" 修剪掉:

$fechaHasta = new DateTime(trim($params["fechaHasta"], '"'));

这应该可以正常工作。

【讨论】:

    【解决方案2】:

    函数trim() 具有从字符串中删除特定字符的选项: 例如:

    echo trim('example"','"');
    

    将输出:示例

    【讨论】:

      【解决方案3】:

      试试strtotime函数,你也可以设置你需要的格式。

      示例:

      $date = date('Y-m-d H:i:s' , strtotime("2016-10-14T22:00:00.000Z"))

      【讨论】:

      • 问题是字符串中的"-引号,在解析之前需要删除。在您的示例中 $date 将是 1970-01-01 00:00:00 因为 strtotime 返回 false
      猜你喜欢
      • 2013-07-14
      • 1970-01-01
      • 1970-01-01
      • 2019-11-08
      • 1970-01-01
      • 1970-01-01
      • 2013-12-07
      • 1970-01-01
      • 2013-04-25
      相关资源
      最近更新 更多