Urs
Urs

Reputation: 5132

How to get time only timestamp from a date in PHP

I have a time field in a PHP that receives Hours and minutes (H:i). This goes into a \Datetime Object. By magic and, in my case, undesiredly, the current Date is added to that time.

I would like to strip the date and keep the time only.

 $timeonly = $this->getDate()->format('H:i');

This gives me the string 10:00.

But now ... how can this string be converted into the desired integer 36000 which is 10h?

I tried strtotime($timeonly) but this added the date again...

Is this even a good idea, and do I not find it because it's so trivial or because this isn't done?

Maybe there's something in DateTime-> like returnTimeWithoutDate?

Upvotes: 0

Views: 1068

Answers (3)

Guillaume
Guillaume

Reputation: 51

You should try sometings like this :

$timeonly = $this->getDate()->format('H:i');
$date = strtotime($timeonly);
echo date('H', $date);

Upvotes: 1

Hack the code :

$timeonly = $this->getDate()->format('H')*3600 + $this->getDate()->format('i')*60;

Upvotes: 1

Sean Bright
Sean Bright

Reputation: 120704

This is trivial with a little bit of math:

function timeToSeconds(\DateTime $dt)
{
    return $dt->format('H') * 3600 + $dt->format('i') * 60;
}

echo timeToSeconds($this->getDate());

Upvotes: 1

Related Questions