javascript 角度js过滤器中的格式化时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30988913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:04:32  来源:igfitidea点击:

Format time in angular js filter

javascriptangularjsdatetimefilter

提问by AlexFF1

How can I reformat time 06:31:04 to display only hh:mm - 06:31

如何重新格式化时间 06:31:04 以仅显示 hh:mm - 06:31

Have tried

试过

$scope.date = '06:31:04';

<p ng-bind="date | date:'HH:mm'"></p>

but time not formatting

但时间没有格式化

How should I make it, thanks

我该怎么做,谢谢

回答by AlexFF1

The best solution was to write a filter

最好的解决方案是编写一个过滤器

angular.module('foo', [])
.filter('formatTime', function ($filter) {
return function (time, format) {
    var parts = time.split(':');
    var date = new Date(0, 0, 0, parts[0], parts[1], parts[2]);
    return $filter('date')(date, format || 'h:mm');
};
});




{{ '06:31:04' | formatTime }}

回答by schirrmacher

See the documentation.

请参阅文档

<p ng-bind="date | date:"hh:mm"}}></p>

Besides I think the format of your date is wrong. Because

此外我认为你的日期格式是错误的。因为

JavaScript Date instance [...] represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC. (source)

JavaScript Date 实例 [...] 代表一个时刻。日期对象基于时间值,该时间值是自 1970 年 1 月 1 日 UTC 以来的毫秒数。(来源

Example: 1288323623006. So your format is not recognizable for the filter. Try:

示例:1288323623006。因此过滤器无法识别您的格式。尝试:

$scope.date = new Date();

If you want to convert a string in your given format to a date, try:

如果要将给定格式的字符串转换为日期,请尝试:

var dateElements = "06:31:04".split(':');
var date = new Date();
date.setHours(time[0]);
date.setMinutes(time[1]);
$scope.date = date;

Then you can format it with the filter.

然后您可以使用过滤器对其进行格式化。

回答by keyvan salimi

u can use the below simple example:

您可以使用以下简单示例:

$scope.date=new Date();

now in the html we have:

现在在 html 中我们有:

    <h2>
        {{ today| date:'hh:mm'  }}
    </h2>