使用momentjs的角度来格式化时间 [英] Use momentjs in angular to format time
问题描述
我无法在角让瞬间格式化我的时间就像我想。我有日期过滤器在这里工作:
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>
我使用火力地堡如果该事项。此外,输入获得的时间就是HTML5输入类型=时间属性。
I am using Firebase if that matters. Also, the input to get the time is the HTML5 input type=time attribute.
推荐答案
当您使用键入=时间
为输入,值存储为一个字符串,它仅重presents一个时间,诸如1:00或13:00。所述amDateFormat滤波器需要,可以是PTED作为其可以是日期对象,对时间戳的数值,或一个适当格式化的字符串日期的日期间$ P $的值。你会得到使用键入=时间
无效的日期字符串使 amDateFormat
不能正确解析的时间值值。
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.
使其工作的最简单的方法是只串联值 event.date
和 event.time
使用 amDateFormat
过滤器之前:
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>
一个更好的解决方案是使用在您的日期和时间,或只是时间传递函数,构造的的东西可以的是PTED为日期间$ P $,或者是一个日期对象。
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>
简单组合函数
$scope.combine = function(date,time) {
if (date && time) {
return date + ' ' + time;
} else {
return "";
}
};
我仍然认为它有点哈克有一个日期添加到这样的时间,但它的作品,你甚至可能最终在数据模型中加入反正在一起。最好的解决方法,我相信将是只是有你可以用它来重新present 1 event.dateAndTime对象的两个的日期和时间 - 你可以使用<$ C $做到这一点C>键入=日期时间本地 HTML5型(至少在Chrome它的工作对我来说)。
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>
下面是一个工作plunker: http://plnkr.co/edit/OERKK9ilxFwUlKLKirtl? p = preVIEW
Here's a working plunker: http://plnkr.co/edit/OERKK9ilxFwUlKLKirtl?p=preview
这篇关于使用momentjs的角度来格式化时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!