简体   繁体   中英

How to convert this date into a different format

Here is my Angular app

var filterData = angular.module('myApp',[]).controller('CallWebApi', function($scope, $http) {
    // Local version of the data
    $http.get('./events.js').
        success(function (data) {
            $scope.data = data.result.items;
            console.log('success ' + data)
        })
        .error(function(data) {
            console.log('failure ' + data)
        });
});
filterData.filter('removeSpacesThenLowercase', function () {
        return function (text) {
            var str = text.replace(/\s+/g, '-');
            return str.toLowerCase();
        };
})

The date looks like this in my data:

        "{B588A80F-A8C0-4A97-A35A-07D81ED53E9B}": {
            "Name": "Expiration Date",
            "Type": "Date",
            "Value": "20150827T000000"
        },

And here is my HTML:

<table>

    <tr>
        <th>Name</th>
        <th>Location</th>
        <th>Date</th>
    </tr>
    <tr ng-repeat="item in data">
        <td><a href="{{ item.Name | removeSpacesThenLowercase }}">{{ item.Fields["{BB2389F3-555B-4FC6-B106-C0A23A55A15F}"].Value }}</a></td>
        <td>{{ item.Fields["{123A77C7-07D5-4CAA-85E0-8F9B9CEE110C}"].Value }}</td>
        <td>{{ item.Fields["{B588A80F-A8C0-4A97-A35A-07D81ED53E9B}"].Value }}</td>
    </tr>

</table>

How do I convert this date:

20150827T000000

Into this format:

08/27/2015?

This should work:

var d = '20150827T000000';
console.log(d.substr(4,2) + '/' + d.substr(6,2) + '/' + d.substr(0,4));
// will give you '08/27/2015'

I created a demo on how you can integrate this in angular: http://plnkr.co/edit/KheLKhLHgGYoF0R5CZgf?p=preview

You can create a filter:

myModule.filter('formatData', function () {
    return function (d) {
        return d.substr(4,2) + '/' + d.substr(6,2) + '/' + d.substr(0,4);
    };
})

and then use it in your view:

 {{test["{B588A80F-A8C0-4A97-A35A-07D81ED53E9B}"].Value|formatData}}

and a fork that formats the data: http://plnkr.co/edit/EReUj4GkhGF36SS6RaX4?p=preview

you could try DateX an eXtension on built-in Date object (ps author)

example:

var date = new DateX( );
var formatted = date.format('Y-m-d H:i:s');
var parsed = DateX.parse(formatted, 'Y-m-d H:i:s');
console.log(formatted);
console.log(parsed.format('Y-m-d H:i:s'));

for your example one can parse it (and validatre it at the same time) into an actual date

var date = DateX.parse("20150827T000000", 'YmdHis');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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