Use momentjs in angular to format time
When you use type=time
for an input, the value is stored as a string which only represents a time, such as "1:00" or "13:00". The amDateFormat filter needs a value that can be interpreted as a date which can be a Date object, a number value for a timestamp, or a properly formatted string date. The time values that you will get using type=time
are not valid date strings so amDateFormat
can't properly parse the value.
The easiest way to make it work is to just concatenate the value of event.date
and event.time
before you use the amDateFormat
filter:
<div class="row">
{{event.date + ' ' + event.time | amDateFormat: 'h:mm a'}}
</div>
A better solution is to use a function where you pass in the date and time, or just the time and construct something that can be interpreted as a date, or is a date object.
<div class="row">
{{ combine(event.date,event.time) | amDateFormat: 'h:mm a'}}
</div>
simple combine function
$scope.combine = function(date,time) {
if (date && time) {
return date + ' ' + time;
} else {
return "";
}
};
I still think it's kinda hacky to have to add a date to the time like that but it works and you may even end up joining them together anyway in your data model. The best solution I believe would be to just have one event.dateAndTime object that you can use to represent both the date and time -- and you can do this using the type=datetime-local
html5 type (at least in Chrome it worked for me).
<dir>Date and time: <input type="datetime-local" ng-model="event.datetime"></dir>
<h4>{{event.datetime | amDateFormat:'MMMM Do'}}</h4>
<div class="row">
event.datetime time: {{ event.datetime | amDateFormat: 'h:mm a'}}
</div>
Here's a working plunker: http://plnkr.co/edit/OERKK9ilxFwUlKLKirtl?p=preview
Related videos on Youtube
Comments
-
Margaret almost 2 years
I'm having trouble getting Moment in Angular to format my time like I would like. I have the date filter working here:
<h4>{{event.date | amDateFormat:'MMMM Do'}}</h4>
But when I try to use this format to print out a time, my time disappears completely out of the browser. This is what I am typing:
<div class="row"> {{event.time | amDateFormat: 'h:mm a'}} </div>
I am using Firebase if that matters. Also, the input to get the time is the HTML5 input type=time attribute.
-
JoseM over 9 years
event.time
doesn't represent a valid "date" value for moment
-
-
Margaret over 9 yearsThank you so much -- I used your second solution (making a function) and it worked great. You rule.
-
JoseM over 9 years@Margaret if my answer worked for you, please don't forget to accept my answer
-
Matt Johnson-Pint over 9 yearsVery nice answer. Thanks!
-
rk rk about 8 yearsWhy can't we do this type of formatting using the default date filter in angularJs.
-
JoseM about 8 yearsYou can do that type of (time) formatting with the default date filter, see the updated plunker: plnkr.co/edit/OERKK9ilxFwUlKLKirtl?p=preview