简体   繁体   English

如何将JSON字符串日期转换为自定义格式日期?

[英]How do I convert JSON string date to a custom format date?

Hi I would like to know how do I convert the JSON string date which comes from a response to format like "8/24/2016". 嗨,我想知道如何将响应中的JSON字符串日期转换为“ 2016/8/24”格式 I made a dateFilter.js bit it didn't work out as I expected so here's what I tried. 我做了一个dateFilter.js,它没有按我预期的那样工作,所以这是我尝试过的。

Here's the dateFilter.js (Actually it didn't work. Error: data recursion) 这是dateFilter.js(实际上不起作用。错误:数据递归)

(function () {

    angular
        .module('myapp')
        .filter('date', function ($filter) {

            return function (input) {

                if (input == null) {

                    return "";
                    }
                var _date = $filter('date')(new Date(input), 'dd/MM/yyyy');

                return _date.toUpperCase();
            };
        });
})();

Here's how I get the JSON with a service ( The code is not complete since I want to show how did I get the response. ) 这是通过服务获取JSON的方式( 代码不完整,因为我想展示如何获取响应。

function GetEmpDetails(successcallback, failcallback) {

            var req = {
                method: 'GET',
                url: 'http://localhost:2222/api/GetEmployees/GetEmployeeDetails',
                headers: {
                    'Content-Type': 'application/json'
                }
            }
            $http(req).then(successcallback, failcallback);
        }

The controller.js controller.js

(function initController() {

    EmployeeService.GetEmpDetails(function (res) {
        $scope.employeeDetails = JSON.parse(res.data);

        //console.log(res.data);

        }
    });

And finally applying the filter to html. 最后将过滤器应用于html。

<table id="basic-datatables" class="table table-striped table-bordered" cellspacing="0" width="100">
   <thead style="text-align:match-parent">
       <tr>
           <th rowspan="1" colspan="1" style="width:195px">First Name</th>
           <th rowspan="1" colspan="1" style="width:195px">Last Name</th>
           <th rowspan="1" colspan="1" style="width:200px">Date Of Birth</th>
           <th rowspan="1" colspan="1" style="width:100px">Gender</th>
           <th rowspan="1" colspan="1" style="width:200px">Email</th>
           <th rowspan="1" colspan="1" style="width:100px">Mobile</th>
           <th rowspan="1" colspan="1" style="width:190px">Designation</th>
           <th rowspan="1" colspan="1" style="width:200px">Date of Join</th>
           <th rowspan="1" colspan="1" style="width:195px">NIC</th>
           <th rowspan="1" colspan="1" style="width:100px">Dept. Name</th>
       </tr>
   </thead>
   <tbody>
       <tr ng-repeat="emp in employeeDetails.slice(((currentPage-1)*itemsPerPage),((currentPage)*itemsPerPage))" style="text-align:center">
           <td>{{emp.fname}}</td>
           <td>{{emp.lname}}</td>
           <td>{{emp.DOB | date}}</td> //applying the filter
           <td>{{emp.gender}}</td>
           <td>{{emp.email}}</td>
           <td>{{emp.mobile_no}}</td>
           <td>{{emp.designation}}</td>
           <td>{{emp.date_of_join | date}}</td> //applying the filter
           <td>{{emp.nic}}</td>
           <td>{{emp.department_name}}</td>
       </tr>
   </tbody>
</table> 

So how would I do this is there's any other way of conversion. 因此,我将如何进行转换?

Final note: right now without the filter: 7/25/2016 12:00:00 AM want to convert to 7/25/2016 最后说明:现在没有过滤器:7/25/2016 12:00:00 AM要转换为7/25/2016

Help would be appreciated. 帮助将不胜感激。

You can first convert the string to actual Date and then apply built in date filter: 您可以先将字符串转换为实际的日期,然后应用内置的日期过滤器:

In your controller: 在您的控制器中:

$scope.convertToDate = function(date){
      var dateOut = new Date(date);
      return dateOut;
};

In your html: 在您的html中:

<td ng-bind="convertToDate(date) |  date:'MM/dd/yyyy'"></td>

Another option can be using moment.js in your filter: 另一个选择是在过滤器中使用moment.js

 moment(input, 'MM/dd/yyyy')

Besides, the reason your filter might not be working is its name. 此外,您的过滤器可能无法正常工作的原因是其名称。 Try changing to anything else, like myDate . 尝试更改为其他任何内容,例如myDate

UPDATE UPDATE

I think I know why you were getting recursion error! 我想我知道您为什么recursion错误! It is because of the name of your custom filter! 这是因为您的自定义过滤器的名称! Your filter is called date and the angular's built in filter is also called date . 您的过滤器称为date ,角度的内置过滤器也称为date Maybe they ended up calling each other and got stuck in recursion. 也许他们最终互相打电话并陷入了递归之中。 Just changing the name should do the trick. 只需更改名称即可解决问题。

Just try this code. 只需尝试此代码。 I think this solves your problem: 我认为这可以解决您的问题:

<td>{{emp.DOB | dateFormat}}</td>

Angular Filter : 角度过滤器:

.filter('dateFormat', function() {
    return function(dt) {
        var dt = new Date(dt);
        return (dt.getMonth()+1)+'/'+dt.getDate()+'/'+dt.getFullYear();
    };
  })

Can be achieved using npm module moment.js. 可以使用npm模块moment.js实现。 i have created a fiddle. 我制造了一个小提琴。 have a look at this. 看看这个。

var date = moment("7/25/2016 12:00:00 AM").date();
var month = moment("7/25/2016 12:00:00 AM").month();
var year = moment("7/25/2016 12:00:00 AM").year();
console.log(''+month+'/'+ date + '/'+ year);

https://jsfiddle.net/Refatrafi/1jq7o2uq/ https://jsfiddle.net/Refatrafi/1jq7o2uq/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM