如何从 PHP 和 Cakephp 中的日期获取小时数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6827668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Hours from Date in PHP & Cakephp?
提问by chetanspeed511987
I want to get Only Hours From date by using PHP & Cakephp function.
我想通过使用 PHP 和 Cakephp 函数从日期中获取仅小时数。
$date = "2011-07-26 20:05:00";
$hours = ?
回答by Clement Herreman
回答by ShoeLace1291
By hours I'm assuming you mean if the time is 8PM or 20:00 hours like it is in your time string then...
我假设你的意思是如果时间是晚上 8 点或 20:00 小时,就像它在你的时间字符串中那样......
$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.
我不太熟悉 PHP 的日期格式,因此您必须参考 PHP.net 以获得正确的格式字符。
回答by krishna Prasad
For 24-hour and 12-hour format, please check below code:
对于 24 小时和 12 小时格式,请检查以下代码:
$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
回答by Affan
At php side you use date('H',strtotime($date));
在 php 端你使用 date('H',strtotime($date));
and at mysql side you can use DATE_FORMATE(NOW(),'%H')
to get only hour
在 mysql 方面,您只能使用DATE_FORMATE(NOW(),'%H')
一个小时
$date
contains date like '2014/08/14' format
$date
包含类似“2014/08/14”格式的日期
To convert date like '2014/08/14' to '14-08-2014' you have to use
要将“2014/08/14”之类的日期转换为“14-08-2014”,您必须使用
date('d-m-Y',strtotime($date));
OR use
或使用
date('d-m-Y',strtotime(str_replace('/','-',$date)))
回答by Gvidon Shmavonyan
回答by Jose Luis
$pattern = '[0-9]{2}:[0-9]{2}';
preg_match('/'.$pattern.'/', '2011-07-26 20:05:00', $matches);
echo $matches[0];
$pattern = '[0-9]{2}:[0-9]{2}';
preg_match('/'.$pattern.'/', '2011-07-26 20:05:00', $matches);
echo $matches[0];