致命错误:未捕获的异常'异常' with message' DateTime :: __ construct():无法解析时间字符串

时间:2014-06-28 12:27:08

标签: php datetime pdo

我收到此错误

  

(!)致命错误:未捕获的异常'异常' with message' DateTime :: __ construct():无法在位置0(0)处解析时间字符串(06-28-2014 07:43:58):意外字符'在/Users/matt/Desktop/Likes/forgot/activate.php第17行

尝试这样做时

//DB query
$stmt = $con->prepare("SELECT token_created_at from reset WHERE token = :urltoken");
$stmt->bindValue(':urltoken', $_GET['token']);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()) {
     $token_created_at = $row['token_created_at'];
}

//Remove after testing
echo $token_created_at;

$my_dt = new DateTime($token_created_at);

//Modify error
$expires_at = $my_dt->modify('+1 hour');

//Return current time to match
$current_time = date('m-d-Y H:i:s ', time());

第17行是$my_dt = new DateTime($token_created_at);,这是我的时间格式06-28-2014 07:43:58

这是我生成token_created_at$time_gen = date('m-d-Y H:i:s ', time());

的方式

3 个答案:

答案 0 :(得分:12)

DateTime解析器传递的日期字符串为not supported。您必须使用createFromFormat创建DateTime对象。此方法允许您在创建新的DateTime对象时指定自定义格式:

$my_dt = DateTime::createFromFormat('m-d-Y H:i:s', $token_created_at);

如果您仍然收到错误消息,表示您的$token_created_at不符合您指定的格式:

$now = date('m-d-Y H:i:s'); //string(19) "06-28-2014 15:00:47"

var_dump(DateTime::createFromFormat('m-d-Y H:i:s', $now));
object(DateTime)#1 (3) {
  ["date"]=>
  string(19) "2014-06-28 15:00:47"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(13) "Europe/Berlin"
}

修改

我看到你的问题 - 格式字符串在s之后有一个空格。格式字符串必须与完全

匹配
$my_dt = DateTime::createFromFormat('m-d-Y H:i:s ', $token_created_at);

答案 1 :(得分:1)

更新了我的回答

function date_time( $date ) {
    if( $date == "" ){
        return "";
    } else {
        // echo $date;
        $my_date  = DateTime::createFromFormat( 'm-d-Y H:i:s', $date );
        // echo '<pre>';
        // print_r($my_date);
        // echo '</pre>';
        $new_date = $my_date->format( 'Y-m-d H:i:s' );
        return $new_date;
    }
}

$save = date_time('06-28-2014 07:43:58');
$my_dt = new DateTime( $save );

//Modify error
$expires_at = $my_dt->modify('+1 hour');
$expires_date = $my_dt->format( 'Y-m-d H:i:s' );

echo $expires_date;
//Return current time to match
$current_time = date('m-d-Y H:i:s', time());
echo $current_time;

答案 2 :(得分:0)

试试这个:

$token_created_at = DateTime::createFromFormat("m-d-Y H:i:s", $token_created_at);
$my_dt = new DateTime($token_created_at->format('Y-m-d H:i:s'));
$expires_at = $my_dt->modify('+1 hour');

这将生成

2014-06-28 08:43:58