【问题标题】:convert birthday date to age in meanjs在meanjs中将生日日期转换为年龄
【发布时间】:2016-05-12 13:42:13
【问题描述】:

我想在我的 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

【问题讨论】:

标签: angularjs meanjs


【解决方案1】:

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

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);
}

希望它会有所帮助。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      这是一个简单的 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 应用于它来将其用作角度函数。像这样:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-08
        • 1970-01-01
        • 2014-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-17
        • 1970-01-01
        相关资源
        最近更新 更多