mskuratowski
mskuratowski

Reputation: 4124

Parse date in AngularJs

I have an date in format /Date(1451602800000)/.

I would like to show this date in 'short' format.

I tried {{myDate | date:'short'}} but the result is /Date(1451602800000)/

Upvotes: 0

Views: 1972

Answers (2)

yuc
yuc

Reputation: 508

here is another approach.
I use the RegExp from @sachila ranawaka
in js:

.filter('regexp', function(){
    return function(input){
        return input.match(/\/Date\(([0-9]*)\)\//)[1];
    };
});

in html:

{{ myDate | regexp | date:'short' }}

this way you can use angular date filter on your preference.

ref: https://docs.angularjs.org/api/ng/filter/date

Upvotes: 1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

Use a custome filter like this

angular.module("app",[])
.controller("ctrl",function($scope){
	$scope.date = "\/Date(1451602800000)\/";
})
.filter("mydate", function() {
    var re = /\/Date\(([0-9]*)\)\//;
    return function(x) {
        var m = x.match(re);
        if( m ) return new Date(parseInt(m[1]));
        else return null;
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  {{date |mydate  }} <br>
  {{date |mydate | date: 'yyyy-MM-dd HH:mm' }}
</div>

Upvotes: 0

Related Questions