【问题标题】:Object of class DateTime could not be converted to string in my query. What am I doing wrong here?在我的查询中,类 DateTime 的对象无法转换为字符串。我在这里做错了什么?
【发布时间】:2016-01-08 09:53:20
【问题描述】:

我在 php/mysql 中有以下查询:

$q2 = $conn3->prepare("SELECT (t.start_time + INTERVAL t.text_duration SECOND) as end_time FROM texts t WHERE t.start_time <= :starttime AND (t.start_time + INTERVAL t.text_duration SECOND) >= :starttime AND t.plot_id = :plot_id LIMIT 1"); 
$q2->bindValue(':starttime', $start_timestamp);
$q2->bindValue(':plot_id', $plot_id);
$q2->execute();
$check2 = $q2->fetch(PDO::FETCH_ASSOC);

$start_time是一个日期时间对象,定义如下:

$date = new DateTime();
$start_timestamp = $date->add(DateInterval::createFromDateString('10 minutes'));

当我运行它时,我收到以下错误:

Catchable fatal error:  Object of class DateTime could not be converted to string in ...

我该如何解决?

【问题讨论】:

    标签: php mysql datetime date-arithmetic


    【解决方案1】:

    当您调用DateTime::add() 时,您只有一个DateTime 对象。 您仍然需要将其转换为时间戳。使用DateTime::getTimestamp() 来执行此操作。 您仍然需要将其转换为日期时间值。使用DateTime::format() 执行此操作。

    $start_timestamp = $date->add(DateInterval::createFromDateString('10 minutes'))->format('Y-m-d H:i:s');
    

    【讨论】:

    • 嘿,对不起,这里有一个混淆,我想避免使用时间戳,只使用日期时间对象,这就是为什么这里的类型是datetime,只有名字暗示它是一个时间戳(但它不是) ... 那么如何在不使用时间戳的情况下修复它呢?
    • 这没有意义。你需要一个日期,而不是一个对象。 starttime 列是什么数据类型?
    • 开始时间的类型是datetime。我想避免使用时间戳并专注于日期时间 - 可以这样做吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 2012-04-29
    • 2013-07-09
    相关资源
    最近更新 更多