计算AngularJS中给定年份的年龄

时间:2015-01-08 14:34:59

标签: angularjs

我是AngularJs的新手。我必须从给出年份计算年龄。我怎么能用PHP?

我的脚本和视图文件如下,

我的.Js:

function mycontroller($scope){
    $scope.sales = [
        {
            name: 'steptoinstall',
            year: 1986,
        }
    ];  }

我的观点.php:

<li ng-repeat="sale in sales" >
    {{sale.name}} {{ **AGE** }}
</li>

和,
如果我有“10-01-1989”的完整日期,那我该怎么办?

3 个答案:

答案 0 :(得分:1)

如果只有年份,

<强> view.PHP

<li ng-repeat="sale in sales" >
    {{sale.name}} {{ yearToAge(sale.year) }}
</li>

.s文件:

$scope.yearToAge= function(y) {
    return new Date().getFullYear() - y;
}

如果给出日期格式,

<强> view.PHP

<li ng-repeat="sale in sales" >
    {{sale.name}} {{ dateToAge(sale.dob) }}   // dob should be in dd/mm/yyyy format
</li>

.s文件:

$scope.dateToAge = function(date1){

var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
var today = curr_date + "-" + curr_month + "-" + curr_year;

var x = date1.split("-");    
var y = today.split("-");
var bdays = x[1];
var bmonths = x[0];
var byear = x[2];
var sdays = y[1];
var smonths = y[0];
var syear = y[2];

if(sdays < bdays)
{
    sdays = parseInt(sdays) + 30;
    smonths = parseInt(smonths) - 1;
    var fdays = sdays - bdays;
}
else{
    var fdays = sdays - bdays;
}

if(smonths < bmonths)
{
    smonths = parseInt(smonths) + 12;
    syear = syear - 1;
    var fmonths = smonths - bmonths;
}
else
{
    var fmonths = smonths - bmonths;
}

var fyear = syear - byear;


return fyear;   

}

答案 1 :(得分:0)

将此添加到您的JS

$scope.ageFromYear = function(year) {
    return new Date().getFullYear() - year;
}

然后,您可以在HTML中执行此操作:

<li ng-repeat="sale in sales" >
    {{sale.name}} {{ ageFromYear(sale.year) }}
</li>

答案 2 :(得分:0)

在PHP中,这个想法是建立在将日期转换为UNIX时间戳,然后转换当前日期的基础上的。然后减去它们,最后将该数字除以一年中的秒数,并得到它的最低点数。

这是如下处理:

$d = '10-01-1989';
$dT = strtotime($d);
$cur = strtotime(date("m-d-Y"));
$diff = $cur - $dT;
$years = floor($diff/(60*60*24*365));
echo $years;

结帐本次演示:http://codepad.org/ErV8RauU