0

I'm new for AngularJs. I have to calculate age from give year. How I can in PHP?

My script and view files are following,

My .Js:

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

My view.php:

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

And,
If I have full date like '10-01-1989', then how can I?

Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289
KarSho
  • 5,699
  • 13
  • 45
  • 78
  • 1
    Do you want to calculate it on the server side (in PHP) or on the client side (in javascript)? In the former case what does it have to do with angular? – David Frank Jan 08 '15 at 14:39
  • possible duplicate of [How to subtract two angularjs date variables](http://stackoverflow.com/questions/15298663/how-to-subtract-two-angularjs-date-variables) – Chuck Le Butt Jan 08 '15 at 14:40

3 Answers3

1

If only year means,

view.PHP

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

.Js File:

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

If Date format given,

view.PHP

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

.Js File:

$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;   

}
Step To Install
  • 138
  • 2
  • 10
0

Add this to your JS

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

Then, you can do this in your HTML:

<li ng-repeat="sale in sales" >
    {{sale.name}} {{ ageFromYear(sale.year) }}
</li>
Rakesh Gopal
  • 580
  • 5
  • 11
0

In PHP, the idea is built on converting the date into UNIX timestamp, then converting the current date too. then subtracting them, and finally dividing that number on the number of seconds in the year and get its floor to get the numbers of years.

This is a handled as following:

$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;

Checkout this DEMO: http://codepad.org/ErV8RauU

SaidbakR
  • 13,303
  • 20
  • 101
  • 195