PHP Timestamp into DateTime

前端 未结 4 657
甜味超标
甜味超标 2021-01-31 01:04

Do you know how I can convert this to a strtotime, or a similar type of value to pass into the DateTime object?

The date I have:

Mon, 1         


        
4条回答
  •  余生分开走
    2021-01-31 01:21

    You don't need to turn the string into a timestamp in order to create the DateTime object (in fact, its constructor doesn't even allow you to do this, as you can tell). You can simply feed your date string into the DateTime constructor as-is:

    // Assuming $item->pubDate is "Mon, 12 Dec 2011 21:17:52 +0000"
    $dt = new DateTime($item->pubDate);
    

    That being said, if you do have a timestamp that you wish to use instead of a string, you can do so using DateTime::setTimestamp():

    $timestamp = strtotime('Mon, 12 Dec 2011 21:17:52 +0000');
    $dt = new DateTime();
    $dt->setTimestamp($timestamp);
    

    Edit (2014-05-07):

    I actually wasn't aware of this at the time, but the DateTime constructor does support creating instances directly from timestamps. According to this documentation, all you need to do is prepend the timestamp with an @ character:

    $timestamp = strtotime('Mon, 12 Dec 2011 21:17:52 +0000');
    $dt = new DateTime('@' . $timestamp);
    

提交回复
热议问题