Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Timestamp into DateTime

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.

like image 671
JREAM Avatar asked Aug 20 '12 13:08

JREAM


People also ask

How do I convert time stamps to dates?

The constructor of the Date class receives a long value as an argument. Since the constructor of the Date class requires a long value, we need to convert the Timestamp object into a long value using the getTime() method of the TimeStamp class(present in SQL package).

What is Strtotime PHP?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.

How can I change Unix timestamp to date in PHP?

To convert a Unix timestamp to a readable date format in PHP, use the native date() function. Pass the format you wish to use as the first argument and the timestamp as the second.

What is timestamp format in PHP?

Summary. The date function in PHP is used to format the timestamp into a human desired format. The timestamp is the number of seconds between the current time and 1st January, 1970 00:00:00 GMT. It is also known as the UNIX timestamp. All PHP date() functions use the default time zone set in the php.ini file.


1 Answers

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); 
like image 155
FtDRbwLXw6 Avatar answered Sep 27 '22 19:09

FtDRbwLXw6