如何在html中将日期和时间转换为特定格式

时间:2017-04-04 06:52:29

标签: html angularjs date

我需要在ng-repeat中以特定格式显示日期和时间。

如果当前时间是上午10点,我从后端获取的日期值是“2017-04-03 05:00:07”到“5小时”。

如果是前一天意味着我需要在昨天显示。如果它超过2天或更多天意味着我需要显示像“Apr 03”这样的月份。如果是前一年意味着我需要显示为“01/02/16”(年/月/日)。

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

任何人都可以帮助我,因为我是这个日期功能的新手。

2 个答案:

答案 0 :(得分:0)

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

使用Angular Filter

示例:{{todayDate |日期:&#34; dd.MM.yy&#34;如果今天日期是2017年4月4日,它将显示&#34; 04.04.17&#34;

答案 1 :(得分:0)

我们可以使用指令执行此操作并比较日期并定义解决方案。

因此,在HTML部分添加此指令

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

Angular Code:

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

希望这有帮助!