我正在使用AngularJS构建一个html应用程序,其中我想在html页面上显示json文件数据。谁能帮我把GMT日期格式从json文件转换为小时:分钟AM/PM
Json文件看起来像这样:
[
{
"startTime": "Sun May 24 2015 01:00:00 GMT+0530 (IST)",
"endTime": "Sun May 24 2015 01:30:00 GMT+0530 (IST)",
"title": "Event 1"
},
{
"startTime": "Sun May 24 2015 04:00:00 GMT+0530 (IST)",
"endTime": "Sun May 24 2015 06:00:00 GMT+0530 (IST)",
"title": "Event 2"
},
{
"startTime": "Sat May 23 2015 20:00:00 GMT+0530 (IST)",
"endTime": "Sat May 23 2015 21:30:00 GMT+0530 (IST)",
"title": "Event 3"
},
{
"startTime": "Sat May 23 2015 21:30:00 GMT+0530 (IST)",
"endTime": "Sat May 23 2015 22:15:00 GMT+0530 (IST)",
"title": "Event 4"
},
{
"startTime": "Sun May 24 2015 02:00:00 GMT+0530 (IST)",
"endTime": "Sun May 24 2015 03:00:00 GMT+0530 (IST)",
"title": "Event 5"
}
]
将json数据分配给作用域变量:
scope.data = [
{
"startTime": "Sun May 24 2015 01:00:00 GMT+0530 (IST)",
"endTime": "Sun May 24 2015 01:30:00 GMT+0530 (IST)",
"title": "Event 1"
},
...
];
在你的html中,你可以像这样使用angularjs日期过滤器:
<div>{{ data[0] | date: 'h:m a' }}</div>
@worldask提供的链接说
日期格式为日期对象, 毫秒(字符串或数字)或各种ISO 8601日期时间字符串格式(如yyyy-MM-ddTHH:mm:ss)。sssZ和它更短例如yyyy-MM-ddTHH:mmZ、yyyy-MM-dd或yyyyMMddTHHmmssZ)。如果没有在字符串输入中指定时区,将考虑时间进入本地时区。
所以我使用自定义过滤器将Sun May 24 2015 01:00:00 GMT+0530 (IST)
转换为毫秒然后使用角过滤器显示为hh:mm AM/PM
<div ng-repeat="date in dateJson">
{{date.startTime | myDateFilter | date:'hh: mm a' }}
</div>
dateJson是你的示例json…
自定义过滤器
app.filter('myDateFilter', function() {
return function(dateString) {
var date = new Date(dateString)
// converting to milliseconds
dateString = date.getTime();
return dateString;
}
});
样本恰好