Rikard
Rikard

Reputation: 7805

PHP convert string with weeks and short month name to date

I am receiving JSON data with a date string with this format:

'Mon Jun 30, 2014'

What would be the way to convert this to a datetime? Checking the PHP functions for this I got unsecure if better to use date_parse_from_format or date_create_from_format.

What are the differences and which would suit better for this task?

Upvotes: 2

Views: 562

Answers (3)

rm-vanda
rm-vanda

Reputation: 3158

The second of the two likely fits you better ---

The first one only breaks down the date into an array, so you can work with the parts, individually.

But the second returns the DateTime object you are looking for.

Upvotes: 1

John Conde
John Conde

Reputation: 219864

DateTime::createFromFormat would work well here. It allows you to format the string easily and also takes timezones into consideration when appropriate and can be easily used in comparisons without having to convert to a timestamp first.

$date = DateTime::createFromFormat('D M d, Y', 'Mon Jun 30, 2014');
echo $date->format('Y-m-d');

Upvotes: 3

AbraCadaver
AbraCadaver

Reputation: 78974

You can convert to a unix timestamp using strtotime(). I don't know what you mean by a "datetime", but if you mean something like for MySQL then you format the timestamp with date() (you can include time but it isn't present in the original string):

echo date('Y-m-d', strtotime($string));

Upvotes: 1

Related Questions