Reputation: 2025
I want to get Only Hours From date by using PHP & Cakephp function.
$date = "2011-07-26 20:05:00";
$hours = ?
Upvotes: 33
Views: 131995
Reputation: 36
As of CakePHP 4.0+ you have the FrozenTime utility class. Just import it.
In a controller:
use Cake\I18n\FrozenTime;
class ExampleController extends AppController {
public function getHour() {
$now = FrozenTime::now();
$hour = $now->hour;
$this->set(compact('hour'));
}
}
Then in your view:
<?= $hour ?>
It should output something like this (assuming it's currently 2:30 PM):
14
Upvotes: 0
Reputation: 275
The date_parse
function will return a fulfilled array of a sections of a datetime. use it like this:
$now = date(now()); // "2021-08-30 21:52:21"
$open = date_parse($now)['hour']; // 21
Upvotes: 1
Reputation: 1
$pattern = '[0-9]{2}:[0-9]{2}';
preg_match('/'.$pattern.'/', '2011-07-26 20:05:00', $matches);
echo $matches[0];
Upvotes: 0
Reputation: 10536
Use the Datetime
class (PHP 5.3 or higher).
$dt = DateTime::createFromFormat("Y-m-d H:i:s", "2011-07-26 20:05:00");
$hours = $dt->format('H'); // '20'
Upvotes: 68
Reputation: 3812
For 24-hour and 12-hour format, please check below code:
$date = "2011-07-26 20:05:00";
echo $hours = date('G', strtotime($date)); // In 24-hour format of an hour without leading zeros
echo '<br>';
echo $hours = date('g', strtotime($date)); // 12-hour format of an hour without leading zeros
// For current timestamp
echo $hours = date('G'); // In 24-hour format of an hour without leading zeros
echo '<br>';
echo $hours = date('g'); //12-hour format of an hour without leading zeros
For reference please check: http://php.net/manual/en/function.date.php
Upvotes: 1
Reputation: 151
Best way to use DateTime class
$my_sql_date = "2011-07-26 20:05:00";
$date_time_obj = new DateTime($my_sql_date);
echo $date_time_obj->format('H');
Upvotes: 1
Reputation: 31
At php side you use date('H',strtotime($date));
and at mysql side you can use DATE_FORMATE(NOW(),'%H')
to get only hour
$date
contains date like '2014/08/14' format
To convert date like '2014/08/14' to '14-08-2014' you have to use
date('d-m-Y',strtotime($date));
OR use
date('d-m-Y',strtotime(str_replace('/','-',$date)))
Upvotes: 1
Reputation: 4698
By hours I'm assuming you mean if the time is 8PM or 20:00 hours like it is in your time string then...
$date = "2011-07-26 20:05:00";
$date = strtotime($date);
echo date('H', $date);
I'm not that familiar with PHP's date formats so you'll have to reference PHP.net for the correct formatting character for that.
Upvotes: 48