2017-04-04 161 views
0

我需要在ng-repeat內以特定格式顯示日期和時間。如何將日期和時間轉換爲html中的特定格式

如果當前時間是上午10點,我從後端獲取的日期值是「2017-04-03 05:00:07」到「5小時」。

如果是前一天的意思,那麼我需要顯示昨天。如果在2天或更多天之前意味着我需要顯示「Apr 03」之類的月份。如果是上一年,意味着我需要顯示爲「01/02/16」(dd/MM/yy)。

<table> 
    <tr ng-repeat="item in messages"> 
    <td><input type="checkbox" class="icheckbox_square-blue" ng-model="messagesinboxCheck"> 
    </td> 
    <td class="mailbox-name"><a>{{item.from}}</a></td> 
    <td class="mailbox-subject">{{item.messagebody.trunc(25)}} 
    </td> 
    <!--<td class="mailbox-attachment"></td>--> 
    <td class="mailbox-type" ng-if="{{item.messagetype}} == 1">SMS</td> 
    <td class="mailbox-type" ng-if="{{item.messagetype}} == 0">Email</td> 
    <td class="mailbox-type" ng-if="{{item.messagetype}} == 2">SMS & Email</td> 
    <td class="mailbox-date">{{item.updateddate}}</td> 
    </tr> 
</table> 
<script> 
var messages = { 
    "json": { 
    "response": { 
     "statuscode": "0", 
     "statusmessage": "Success", 
     "data": { 
     "inboxmessages": [{ 
      "modulereferenceid": 23671, 
      "transactionid": 18969, 
      "messagebody": "Testing message", 
      "messagetype": 1, 
      "createddate": "2017-04-03 05:00:07", 
      "updateddate": "2017-04-03 05:00:07", 
      "forward": false, 
      "from": "dinesh", 
      "deleted": false, 
      "enablecomments": false, 
      "url": "/GroupzMobileApp/inbox/avNTaab2hMaaaaeNar6yaaabwMaaanQa" 
     }] 
     }, 
     "lastsynchtime": "2017-04-04 06:14:09" 
    } 
    } 
} 
</script> 

任何人都可以幫助我,因爲我是新的日期功能。

+0

編寫一個過濾器,並按照您在過濾器中的要求轉換日期。 –

回答

0
<td class="mailbox-date">{{item.updateddate}}</td> 

使用Angular Filter

例如:{{todayDate | date:「dd.MM.yy」}}如果todayDate是2017年4月4日,它會顯示「04.04.17」

0

我們可以使用指令來做這件事,比較幾天並定義解決方案。

因此,在你的HTML部分添加此配置

<tr ng-repeat="item in messages" my-directive="item"> 

角代碼:

app.directive('myDirective', function($filter) { 
return { 
    restrict: "A", 
    scope: { 
     myDirective: '=' 
    }, 
    link: function(scope, element, attrs) { 
     var date1 = new Date(scope.myDirective.updateddate); 
     var date2 = new Date(); 
     var timeDiff = Math.abs(date2.getTime() - date1.getTime()); 
     var diffDays = Math.ceil(timeDiff/(1000 * 3600 * 24)); 
     if (diffDays == 1) { 
      scope.myDirective.updateddate = 'yesterday' 
     } else if (diffDays > 2 && diffDays <= 365) { 
      scope.myDirective.updateddate = $filter('date') scope.myDirective.updateddate, 'dd-MMM'); 
    } 
    else if (diffDays > 365) { 
     scope.myDirective.updateddate = $filter('date') scope.myDirective.updateddate, 'dd-MM-YYYY'); 
} } }; }); 

希望這有助於!

+0

我在第**行「scope.myDirective.updateddate = $ filter('date')scope.myDirective.updateddate,'dd-MMM');」** – sudarsan

相關問題