简体   繁体   中英

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 = ?

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'

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.

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)))

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

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

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');

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM