Christos Hayward
Christos Hayward

Reputation: 5993

How do I ask AngularJS to format a localtime for a timestamp?

I have a two-element array: the first element is a string, and the second is an integer number of milliseconds since epoch. I can display the integer number of milliseconds, but I'm getting an error when attempting to get a locale string for the date.

The two lines of code that result in the timestamp being displayed as integer are:

<div class='timestamp' ng-bind='monologues[session][1]'></div>
<div class='timestamp' ng-bind='new Date(monologues[session][1]).toLocaleString()'></div>

The Chrome error console gives:

Error: [$parse:syntax] http://errors.angularjs.org/1.3.0-beta.3/$parse/syntax?p0=Date&p1=is%20an%20unexpected%20token&p2=5&p3=new%20Date(monologues%5Bsession%5D%5B1%5D).toLocaleString()&p4=Date(monologues%5Bsession%5D%5B1%5D).toLocaleString()
    at Error (native)
    at http://localhost:8000/media/js/angular.min.js:6:456
    at $a.throwError (http://localhost:8000/media/js/angular.min.js:164:422)
    at $a.parse (http://localhost:8000/media/js/angular.min.js:163:299)
    at http://localhost:8000/media/js/angular.min.js:96:31
    at k (http://localhost:8000/media/js/angular.min.js:102:163)
    at g.$watch (http://localhost:8000/media/js/angular.min.js:103:321)
    at http://localhost:8000/media/js/angular.min.js:188:247
    at H (http://localhost:8000/media/js/angular.min.js:52:492)
    at g (http://localhost:8000/media/js/angular.min.js:46:28) <div class="timestamp ng-binding" ng-bind="new Date(monologues[session][1]).toLocaleString()"> 

First, am I approaching things correctly by attempting to bind on a JavaScript expression calculating what I want to display?

Second, how should I approach things where the server is (by my choice) giving an integer number of milliseconds, and I would like to display a corresponding formatted locale time for the user?

Upvotes: 3

Views: 2126

Answers (1)

Evandro Silva
Evandro Silva

Reputation: 1402

Using $watch

You can set this in your controller:

$scope.$watch('monologues', function() {
    $scope.newProp = new Date($scope.monologues[$scope.session][1]).toLocaleString();
});

and then use it in your view:

<div class='timestamp' ng-bind='newProp'></div>

Using a filter

You can also create a filter for that, like so:

myApp.filter('toLocale', function () {
    return function (item) {
        return new Date(item).toLocaleString()
    };
});

and use it on the view:

<div class='timestamp'>{{ monologues[session][1] | toLocale }}</div>

Upvotes: 5

Related Questions