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.
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