Reputation: 5124
Trying to get the hours in 24 hours format from a datetime and nothing works:
$date=date_create("now");
date_add($date,date_interval_create_from_date_string('3 hours'));
$finalDate = date_format($date,"Y-m-d H:i:s");
// $finalDate is "2013-12-25 15:06:45"
Tried the following:
date('H', $finalDate)); // getting 02
date('G', $finalDate)); // getting 02
$finalDate->hours); // getting nothing
date_format($finalDate,"H")); // getting nothing
Read all posts in this site, nothing solved it for me...
Upvotes: 0
Views: 182
Reputation:
Please use the newer DateTime object. I also added the out commented variant of how to see the difference between two different DateTime objects.
$date1 = new DateTime('2013-12-15 12:00:00');
$date2 = new DateTime('2013-12-25 13:30:30');
//$interval = $date1->diff($date2);
//$diff = $interval->format('%d');
//echo $diff;
echo $date1->format('H');
You can use the PDO variant of $date->add()
to write what you did a little cleaner :)
Upvotes: 1
Reputation: 160863
$date
is already an DateTime object.
All you need to do is:
$hour = date_format($date, 'H');
or
$hour = $date->format('H');
PS: Object oriented style is recommended over Procedural style.
Upvotes: 3
Reputation:
With DateTime
and "object syntax":
<?php
$date = new DateTime();
$date->modify('+3 hours');
echo $date->format('H');
?>
Upvotes: 2
Reputation: 2654
Try this:
$timeStr=strtotime($finalDate);
echo date('H', $timeStr);
Upvotes: 0