Check if timestamp is today
I've got a tim开发者_如何转开发estamp in the following format (Which can easily be changed thanks to the beauties of PHP!).
2011-02-12 14:44:00
What is the quickest/simplest way to check if this timestamp was taken today?
I think:
date('Ymd') == date('Ymd', strtotime($timestamp))
if (date('Y-m-d') == date('Y-m-d', strtotime('2011-02-12 14:44:00'))) {
// is today
}
$offset = date('Z'); //timezone offset in seconds
if (floor(($UNIX_TIMESTAMP + $offset) / 86400) == floor((mktime(0,0,0) + $offset) / 86400)){
echo "today";
}
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...
in your case :
if(compareDates("now",'2011-02-12 14:44:00','Y-m-d')===0){
// do stuff
}
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
(date('Ymd') == gmdate('Ymd', $db['time']) ? 'today' : '')
are you mean this ?
if( strtotime( date( 'Y-m-d' , strtotime( '2011-02-12 14:44:00' ) ) ) == strtotime( date( 'Y-m-d' ) ) )
{
//IS TODAY;
}
精彩评论