chetanspeed511987
chetanspeed511987

Reputation: 2025

How to get Hours from Date in PHP & Cakephp?

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

Answers (8)

Abel Bottello
Abel Bottello

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

Yuri
Yuri

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

Jose Luis
Jose Luis

Reputation: 1

$pattern = '[0-9]{2}:[0-9]{2}'; preg_match('/'.$pattern.'/', '2011-07-26 20:05:00', $matches); echo $matches[0];

Upvotes: 0

Clement Herreman
Clement Herreman

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

krishna Prasad
krishna Prasad

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

Gvidon Shmavonyan
Gvidon Shmavonyan

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

Affan
Affan

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

ShoeLace1291
ShoeLace1291

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

Related Questions