PHP:生日检查今天的日期

PHP:生日检查今天的日期

问题描述:

我有用户的生日保存在birthday为1999-02-26。PHP:生日检查今天的日期

如何检查生日是否是今天?

if(date('m-d') == ..? 

if(date('m-d') == substr($birthday,5,5)) 

要添加什么蒂姆说:

if(date('m-d') == substr($birthday,5,5) or (date('y')%4 <> 0 and substr($birthday,5,5)=='02-29' and date('m-d')=='02-28')) 
+5

你也应该允许泰德的生日在2004年2月29日 - 2011年,他将迎来在02-28他的生日。 – 2010-10-06 14:41:59

+0

尼斯认为蒂姆,这怎么可能呢? – Johnson 2010-10-06 14:50:56

+0

谢谢蒂姆。我已经改变了答案。 – CristiC 2010-10-06 15:07:43

这个答案应该的工作,但是这取决于strtotime能找出你的数据库的日期格式:

$birthDate = '1999-02-26'; // Read this from the DB instead 
$time = strtotime($birthDate); 
if(date('m-d') == date('m-d', $time)) { 
    // They're the same! 
} 
+0

_Should_在这个复杂的世界里是不够的。这些日期和时间计算总是倾向于在不同的边缘和事件中存在隐藏的困难。 2月29日出生的人生日很困难。而检查闰年是复杂的。这值得一些现成的解决方案。 – Gherman 2014-09-29 11:06:05

+0

@德国好吧,strtotime是由第三方写的......顺便说一句,我注意到当我写这个时,我意外地链接到了strptime的手册页......这是一个不同的功能。顺便说一句,因为这个答案是写的,PHP有DateTime对象和相关的功能添加到它。 – Powerlord 2014-09-29 13:43:35

从PHP 5.2起:

if (substr($dateFromDb, -5) === date_create()->format('m-d')) { 
    // Happy birthday! 
} 

<?php 
/** 
* @param string $birthday Y-m-d 
* @param int $now 
* @return bool 
*/ 
function birthdayToday($birthday, $now = null) { 
    $birthday = substr($birthday, -5); 
    if ($now === null) { 
     $now = time(); 
    } 
    $today = date('m-d', $now); 
    return $birthday == $today || $birthday == '02-29' && $today == '02-28' && !checkdate(2, 29, date('Y', $now)); 
}