在meanjs中将生日日期转换为年龄

convert birthday date to age in meanjs

我想在我的 meanjs 应用程序中显示所有用户的年龄。 我如何显示年龄而不是显示生日。我的 plunk demo

控制器:

$scope.agedate = new Date();
   $scope.calculateAge = function calculateAge(birthday) { 
    var ageDifMs = Date.now() - birthday.getTime();
    var ageDate = new Date(ageDifMs); // miliseconds from epoch
    return Math.abs(ageDate.getUTCFullYear() - 1970);
}

Html:

<p ng-bind="items.user.displayName"></p>
<p ng-bind="items.user.dateofbirth | date"></p>
<p ng-bind="calculateAge(items.user.dateofbirth)"></p>

我的数据:-

$scope.items = {
"_id": "5733163d4fc4b31d0ff2cb07",
"user": {
"_id": "5732f3954fc4b31d0ff2cb05",
"displayName": "karthi keyan",
"dateofbirth": "1991-10-04T18:30:00.000Z",
"profileImageURL": "./modules/users/client/img/profile/uploads/ed948b7bcd1dea2d7086a92d27367170"
},
"__v": 0,
"comments": [],
"content": "this is testing purpose for e21designs",
"categoryone": "Moral Ethics",
"category": "Anonymous Question",
"title": "Worried",
"created": "2016-05-11T11:23:41.500Z",
"isCurrentUserOwner": true
};

我的plunk demo

您的代码几乎可以满足您的要求。

它在 dateofbirth 属性 中有问题,因为它是一个字符串(根据你的例子。

要将其显示为您正在使用 date 过滤器为您处理的日期。

但是,在您的 calculateAge 函数中,您需要将字符串转换为 Date

尝试以下操作:

$scope.calculateAge = function calculateAge(birthday) { // birthday is a string
    var ageDifMs = Date.now() - new Date(birthday).getTime(); // parse string to date
    var ageDate = new Date(ageDifMs); // miliseconds from epoch
    return Math.abs(ageDate.getUTCFullYear() - 1970);
}

希望对您有所帮助。

请注意,此问题与 angularjs 完全无关。它是纯粹的 Javascript 日期差异计算。 我强烈建议使用像 (momentjs)[http://momentjs.com/] 这样的第三方库来进行这样的计算,以帮助您解析字符串格式的日期。

这是 javascript 中的一个简单函数,用于计算日期格式 "YYYY-MM-DD" 的年龄。其中函数的 dateString 参数是出生日期。

function calculateAge(dateString) {
  var today = new Date();
  var birthDate = new Date(dateString);
  var age = today.getFullYear() - birthDate.getFullYear();
  var m = today.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
      age--;
  }
  return age;
}

您可以通过对其应用 $scope 将其用作 angular 函数。像这样:

$scope.calculateAge = function(dateString) {
  var today = new Date();
  var birthDate = new Date(dateString);
  var age = today.getFullYear() - birthDate.getFullYear();
  var m = today.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
      age--;
  }
  return age;
}