我所见过的所有功能都与出生日期有所不同,我希望在几个月甚至几天内获得年龄。
php中的示例:
$date = "2015-05-23";
/* whatever */
echo "Has 2 months and 8 days";
$date = "2012-10-30";
/* whatever */
echo "Has 2 years and 2 months";
在javascript / jquery或php中没关系。
谢谢大家!
答案 0 :(得分:0)
您可以在PHP中使用此代码来获取从日期到当前日期或其他日期的天,月和年的差异
<?php
$date = "2015-07-17";
$difference = strtotime(date("Y-m-d")) - strtotime($date);
$days = abs(round($difference / 86400,0));
$years = abs(round($days /365,0));
$months = abs(round($years/12,0));
echo "Difference in Days: $days| Months: $months| Years: $years";
如果你想在一个字符串中输入一个数字,你可以使用stackoverflow中提到的答案...
答案 1 :(得分:0)
在php中你可以试试这个:
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo ($diff->format("%a"));
它将返回以天为单位的差异,也可以按月和年来换算。
答案 2 :(得分:0)
我修改了一些代码来获得我想要的东西。这项工作非常完美,除了所有例外情况(如果某些年/月/日为0,则不显示)。
如果有人需要,我会在PHP中与您分享我的代码。
echo getAge("10-02-2014");
function getAge($fecha) {
/* $fecha => d-m-Y (in this format!!) */
$dob = strtotime($fecha);
$current_time = time();
$age_years = date('Y',$current_time) - date('Y',$dob);
$age_months = date('m',$current_time) - date('m',$dob);
$age_days = date('d',$current_time) - date('d',$dob);
if ($age_days<0) {
$days_in_month = date('t',$current_time);
$age_months--;
$age_days= $days_in_month+$age_days;
}
if ($age_months<0) {
$age_years--;
$age_months = 12+$age_months;
}
$todayString = date('d',$current_time).'-'.date('m',$current_time).'-'.date('Y',$current_time);
/* keep in mind $today is always superior than $fecha */
if($fecha == $todayString){
return "Today";
} else if(date('Y',$dob) == date('Y',$current_time) && $age_months == "0") {
return $age_days . " day".plural($age_days);
} else if(date('Y',$dob) == date('Y',$current_time) && $age_days != "0") {
return $age_months ." month".plural($age_months)." and ".$age_days ." day".plural($age_days);
} else if(date('Y',$dob) == date('Y',$current_time) && $age_days == "0") {
return $age_months . " month".plural($age_months);
} else if($age_years != "0" && $age_months != "0" && $age_days == "0") {
return $age_years . " year".plural($age_years)." and ".$age_months." month".plural($age_months);
} else if($age_years != "0" && $age_months == "0" && $age_days != "0") {
return $age_years . " year".plural($age_years)." and ".$age_days." day".plural($age_days);
} else if($age_years != "0" && $age_months == "0" && $age_days == "0") {
return $age_years . " year".plural($age_years);
} else { /* if you want to show the days always, add ----> ." and ".$age_days." day".plural($age_days) <---- below */
return $age_years. " year".plural($age_years)." and ".$age_months." month".plural($age_months);
} }
function plural($num) {
if($num!="1"){
return "s";
} }
啊,记住,也许你需要先设置时区。
date_default_timezone_set("Europe/Madrid");