dongwu8050 2016-03-11 09:44
浏览 190
已采纳

无法在PHP中解析时间字符串

I need to create a DateTime from the value received from a form. The problem is that the value is received like a string: "2016-10-10T08:29:06.959Z" and I need to received like 2016-10-10T08:29:06.959Z without quotes, because if I receive with quotes I've got the next error:

DateTime::__construct(): Failed to parse time string ("2016-10-14T22:00:00.000Z") at position 0 ("): Unexpected character

When I try to transform the value to a DateTime with:

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

If I try to use:

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

I've got an empty object in $fecha2.

The form from where I send the data is:

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

So, what I have to do to send the value without quotes or transform the value received in DateTime.

  • 写回答

3条回答 默认 最新

  • douzhangjian1505 2016-03-11 09:51
    关注
    $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",
       }
    

    So you just trim the " away:

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

    This should work fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?