php 检查时间戳是否为今天
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5775076/
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
Check if timestamp is today
提问by Web_Designer
I've got a timestamp in the following format (Which can easily be changed thanks to the beauties of PHP!).
我有以下格式的时间戳(由于 PHP 的优点,可以轻松更改!)。
2011-02-12 14:44:00
2011-02-12 14:44:00
What is the quickest/simplest way to check if this timestamp was taken today?
检查这个时间戳是否是今天采取的最快/最简单的方法是什么?
回答by Rudie
I think:
我认为:
date('Ymd') == date('Ymd', strtotime($timestamp))
回答by deceze
if (date('Y-m-d') == date('Y-m-d', strtotime('2011-02-12 14:44:00'))) {
// is today
}
回答by Daniel Fontes
$offset = date('Z'); //timezone offset in seconds
if (floor(($UNIX_TIMESTAMP + $offset) / 86400) == floor((mktime(0,0,0) + $offset) / 86400)){
echo "today";
}
回答by yorg
This is what i use for this kind of task :
这就是我用于此类任务的方法:
/** date comparator restricted by $format.
@param {int/string/Datetime} $timeA
@param {int/string/Datetime} $timeB
@param {string} $format
@returns : 0 if same. 1 if $timeA before $timeB. -1 if after */
function compareDates($timeA,$timeB,$format){
$dateA=$timeA instanceof Datetime?$timeA:(is_numeric($timeA)?(new \Datetime())->setTimestamp($timeA):(new \Datetime("".$timeA)));
$dateB=$timeB instanceof Datetime?$timeB:(is_numeric($timeB)?(new \Datetime())->setTimestamp($timeB):(new \Datetime("".$timeB)));
return $dateA->format($format)==$dateB->format($format)?0:($dateA->getTimestamp()<$dateB->getTimestamp()?1:-1);
}
compare day : $format='Y-m-d'.
compare month : $format='Y-m'.
etc...
比较日期:$format='Ym-d'。
比较月份:$format='Y-m'。
等等...
in your case :
在你的情况下:
if(compareDates("now",'2011-02-12 14:44:00','Y-m-d')===0){
// do stuff
}
回答by Rossitten
(date('Ymd') == gmdate('Ymd', $db['time']) ? 'today' : '')
回答by trante
I prefer to compare timestamps (rather then date strings), so I use this to check today.
我更喜欢比较时间戳(而不是日期字符串),所以我今天用它来检查。
$dayString = "2011-02-12 14:44:00";
$dayStringSub = substr($dayString, 0, 10);
$isToday = ( strtotime('now') >= strtotime($dayStringSub . " 00:00")
&& strtotime('now') < strtotime($dayStringSub . " 23:59") );
Fiddle: http://ideone.com/55JBku
小提琴:http: //ideone.com/55JBku
回答by DJafari
are you mean this ?
你是这个意思吗?
if( strtotime( date( 'Y-m-d' , strtotime( '2011-02-12 14:44:00' ) ) ) == strtotime( date( 'Y-m-d' ) ) )
{
//IS TODAY;
}