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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c