PHP时间戳记到DateTime [英] PHP Timestamp into DateTime

查看:176
本文介绍了PHP时间戳记到DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您是否知道如何将其转换为strtotime或类似类型的值以传入 DateTime 对象?



我有日期:

  Mon,12 Dec 2011 21:17:52 +0000 

我曾尝试过:

  $ time = substr($ item-> pubDate,-14); 
$ date = substr($ item-> pubDate,0,strlen($ time));

$ dtm = new DateTime(strtotime($ time));
$ dtm-> setTimezone(new DateTimeZone(ADMIN_TIMEZONE));
$ date = $ dtm-> format('D,M dS');
$ time = $ dtm-> format('g:i a');

以上是不正确的。如果我循环了很多不同的日期,它的日期相同。

解决方案

您不需要将字符串转换为一个时间戳,以便创建 DateTime 对象(实际上,它的构造函数甚至不允许你这样做,你可以告诉)。您可以按照原样简单地将您的日期字符串输入到 DateTime 构造函数中:

  //假设$ item-> pubDate是Mon,12 Dec 2011 21:17:52 +0000
$ dt = new DateTime($ item-> pubDate);就是说,如果你有一个你希望使用的时间戳而不是一个字符串,那么你就可以可以使用 DateTime :: setTimestamp()

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

编辑(2014-05-07):



我当时没有意识到这一点,但是 DateTime 构造函数支持创建实例直接从时间戳。根据此文档,您需要做的只是添加时间戳与 @ 字符:

  $ timestamp = strtotime('Mon ,2011年12月12日21:17:52 +0000'); 
$ dt = new DateTime('@'。$ timestamp);


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, 12 Dec 2011 21:17:52 +0000

What I've tried:

    $time = substr($item->pubDate, -14);
    $date = substr($item->pubDate, 0, strlen($time));

    $dtm = new DateTime(strtotime($time));
    $dtm->setTimezone(new DateTimeZone(ADMIN_TIMEZONE));
    $date = $dtm->format('D, M dS');
    $time = $dtm->format('g:i a');

The above is not correct. If I loop through a lot of different dates its all the same date.

解决方案

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

这篇关于PHP时间戳记到DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆