由于PHP提供了丰富的类来处理日期, 因此使用PHP操纵日期已变得非常容易。如果你不知道如何获取两个给定日期之间的年(和其他值)之间的差异, 那么本文可能对你有用。
以下代码段显示了如何检索日期与现在之间的时差。 DateTime对象的diff属性允许你获取有关给定日期之间范围的详细信息:
- 年($ diff-> y)
- 个月($ diff-> m)
- 天($ diff-> days)
- 小时($ diff-> h)
- 秒($ diff-> s)
$stringDate = "12/04/1950";
$date = new DateTime($stringDate);
$now = new DateTime();
$interval = $now->diff($date); // the interva contains information about the difference between now and the given date
var_dump($interval);
echo "There are ". $interval->y. " years between the given date and today";
// The output of the var_dump should be something like :
object(DateInterval)#3 (15) {
["y"]=>
int(65)
["m"]=>
int(3)
["d"]=>
int(9)
["h"]=>
int(0)
["i"]=>
int(21)
["s"]=>
int(54)
["weekday"]=>
int(0)
["weekday_behavior"]=>
int(0)
["first_last_day_of"]=>
int(0)
["invert"]=>
int(1)
["days"]=>
int(23841)
["special_type"]=>
int(0)
["special_amount"]=>
int(0)
["have_weekday_relative"]=>
int(0)
["have_special_relative"]=>
int(0)
}
function getDifferenceInYearsBetween($startDate, $limitDate){
$start = new DateTime($startDate);
$end = new DateTime($limitDate);
$interval = $end->diff($start);
return $interval->y;
}
//call it like
//month/day/year
echo getDifferenceInYearsBetween("11/19/1997", "11/19/2012");
注意:如果你不能使用DateTime类(由于php版本5.2或其他原因), 则应该可以使用以下代码片段查找日期:
// Note the format of the string ddate
$birthDate = "12/04/1950";
//explode the date to get month, day and year (careful with the separator character, change it to - if you use that sign)
$birthDate = explode("/", $birthDate);
//get age from date or birthdate
$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
? ((date("Y") - $birthDate[2]) - 1)
: (date("Y") - $birthDate[2]));
echo "Age is:" . $age; // 65
作为文章的标题, 此函数将自身限制为仅几年, 但是如果你有php版本的限制, 此功能将非常有用。
评论前必须登录!
注册