matthewaveryusa
matthewaveryusa

Reputation: 652

How to go from mktime to datetime object?

I have an mktime that I want to have return a datetime object. The best way I came up with seems way too convoluted:

DateTime::createFromFormat("Y-m-d H:i:s",date("Y-m-d H:i:s",mktime(0, 0, 0, $data[$j]['month'], $data[$j]['day'],$data[$j]['year'])));

any better ways?

Upvotes: 3

Views: 8853

Answers (2)

SenG
SenG

Reputation: 731

Why don't you get rid of mktime and make use of native methods of DateTime class?

$midOfDay->setTime(12, 0, 0);
$midOfDay->setDate($data[$j]['year'], $data[$j]['month'], $data[$j]['day']);

Upvotes: 1

Emil Vikström
Emil Vikström

Reputation: 91963

The DateTime constructor can take a UNIX timestamp as parameter, so just use the return value from mktime directly in the constructor if you prefix it with @:

$datetimeobject = new DateTime('@' . mktime(0, 0, 0, $data[$j]['month'], $data[$j]['day'],$data[$j]['year']));

Or you can skip the mktime step completely since DateTime can also parse date strings (but this will be more resource hungry, if you're into micro-optimization):

$datetimeobject = new DateTime($data[$j]['year'] .'-'. $data[$j]['month'] .'-'. $data[$j]['day']);

Upvotes: 5

Related Questions