How can I convert a date and time into a time only using angular-moment?

828 views Asked by At

So I have dates like this:

$scope.sample_time = "September 14th 2017, 1:00:00 pm";

And in my view, I want to only show the time like example 1:00 pm.

Using angular-moment, I tried something like {{ sample_time | amParse:'HH:mm a'}} but I get 2017-09-14T06:00:00.000Z.

Am I missing something here? Any help would be much appreciated.

2

There are 2 answers

0
Fetrarij On BEST ANSWER

Because "September 14th 2017, 1:00:00 pm" is not a default valid date, you need to parse it first, by the corresponding format you use (which is 'MMMM Do YYYY, h:mm:ss a' ), then you got a valid date and can use amDateFormat to format it: amDatFormat:'HH:mm a'

{{ sample_time | amParse:'MMMM Do YYYY, h:mm:ss a' | amDateFormat: 'H:mm s'}}

a plunker: http://plnkr.co/edit/RocNLPq6uBlFnccLFB8N?p=preview

2
redanesc On

what i do is like this:

{{ getLocalDate(sample_time) | date: "hh:mm a"}}

get local date converts the current date

 $scope.getLocalDate = function (date) {

        return new Date(moment.utc(date));
    }

and this outputs the desired time format you want.

Im not sure if this is the best way. I hope this helps