How do I format date in Angular js


#1

Hello everyone, I tried to use $http to retrieve data from my database and it seemed working fine. However I have a column with datetime2 format and it showed in this format:

/Date(1495119764040)/

How could I show that date in dd-MM-yyyy?

Thanks.


#2

Using template binding: HTML

{{ date_expression | date : format : timezone}}

Inside a JS File:

$filter('date')(date, format, timezone)


#3

Thanks for your reply. If I used set the model this way:

$scope.currentDate = new Date();

And call it in the controller like this:

{{currentDate | date:'dd/MM/yyyy'}}

It works fine. However, my date was converted to this /Date(1495119764040)/ and this doesn't work. You know what's happening?

Thanks.


#4

Just notice that my date was automatically converted to seconds that's how it comes up to 1495119764040 seconds

There should be an easy way to quickly convert this to date. But I could not figure out how.

Thanks.


#5

Is your html referring to your controller?

EXAMPLE CONTROLLER:

function Control($currentDate)
{
    $currentDate.date = new Date();
}

EXAMPLE HTML FILE:

<div ng-app ng-controller="Control">
    {{date | date:'dd-MM-yyyy'}}
</div>

#6

The above line will give me something like Thu, 24 May 2017 15:02:44.040 GMT but in my case the date has been automatically converted to seconds 1495119764040 when retrieving from the database. If you use this site

https://www.epochconverter.com/

1495119764040 seconds is actually Thu, 18 May 2017 15:02:44.040 GMT.

So I need a way to convert the seconds back into the date format and then I can use date:'dd-MM-yyyy'. Otherwise, Augular doesn't know.

Please let me know if you need more explanation.


#7

Here's a function in JS that converts seconds to days, hours, and minutes,

app.filter('secondsToDateTime', [function() {
    /**
     * This code returns a date string formatted manually.
     * Code "new Date(1970, 0, 1).setSeconds(seconds)" returns malformed output on days.
     * Eg. 4 days, magically becomes 5, 15 becomes 16 and so on...;
     * */
    return function(seconds) {
    var days = Math.floor(seconds/86400);
    var hours = Math.floor((seconds % 86400) / 3600);
    var mins = Math.floor(((seconds % 86400) % 3600) / 60);
    var secs = ((seconds % 86400) % 3600) % 60;
    return (days > 0 ? days+'d ' : '') + ('00'+hours).slice(-2) +':' + ('00'+mins).slice(-2)+':' + ('00'+secs).slice(-2);
    };
}]);