[英]How to parse data from an extracted JSON object property using AngularJS?
[英]How to parse date field from json using angularJs filter
这是我从json文件/Date(1435837792000+0000)/
我需要以以下格式显示日期Oct 29, 2010 9:10:23 AM
Javascript中的Date原型没有像format()这样的函数。 但是有以下方法:
getDate() // Returns the date
getMonth() // Returns the month
getFullYear() // Returns the year
getHours() // Returns the hour
getMinutes() // Returns the minute
getSeconds() // Returns the second
您可以使用以下方式自己形成字符串:
function formatDate(dt) {
var monthNames = ["January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"];
var h = dt.getHours(), am;
if (h > 12) {
am = 'pm';
h = h - 12;
} else {
am = 'am';
}
return monthNames[dt.getMonth()].substring(0, 3) + ' ' +
dt.getDate() + ', ' + dt.getFullYear() + ' ' +
h + ':' + dt.getMinutes() + ':' + dt.getSeconds() + ' ' +
am;
}
console.log(formatDate(new Date(1435837792000+0000)));
如果您发现自己需要更多的日期解析和格式设置,请查看Momentjs库。 现在,您可以执行以下操作:
moment(new Date(1435837792000+0000)).format("MMM D, YYYY hh:mm:ss A")
您可以从json中提取此值。
将其分配给控制器中的作用域变量。 yourCtrl.js
json = { name: 'stackoverflow',
date: 1435837792000+0000
};
$scope.today = new Date(json.date); //This converts the date value from the json to a healthy looking date something like this `2015-07-02T11:49:52.000Z`
today.html
{{ today | date:'medium' }}
此角度过滤器将以所需的日期格式显示您的日期。 2010年10月29日,上午9:10:23
编辑:
$scope.today = Date(1435837792000+0000);
$scope.today = new Date($scope.today);
然后按照如下方式使用角度滤镜对其进行管道传输
{{ today | date:'MMM d, y hh:mm:ss' }}
{{ today | date:'MMM d, y hh:mm:ss' }}
或{{ today | date:'medium' }}
{{ today | date:'medium' }}
根据您的要求。
首先将时间戳从JSON转换为Date
变量,这是一个残酷的match
:
var json = { "PublishDate": "\/Date(1435757849000+0000)\/" };
var timestamp = parseInt(json.PublishDate.match(/\d+/)[0],10);
var date = new Date(timestamp);
然后,古怪(尚未本地化)和可能不可靠的非标准的.toDateString()
和.toLocaleTimeString()
的混合可能会接近:
date = date.toDateString() + ' ' + date.toLocaleTimeString('en');
alert( date === 'Wed Jul 01 2015 3:37:29 PM' );
还有.toGMTString()
返回Thu, 02 Jul 2015 11:49:52 GMT
(RFC 1123)。
使用JS将其转换为Date对象,然后将其转换为date函数。
<html>
<head>
<script>
function jsonDatetoJSDate(){
var dateFromServer = "/Date(1435837792000+0000)/";
//Javascript conversion
var prsdDt = new Date(parseInt(dateFromServer.substr(6)));
//getting Date Object
var uDate = new Date(prsdDt);
alert(uDate);
}
</script>
</head>
<body onload="javascript:jsonDatetoJSDate()">
Use Date Function on javaScript
</body>
</html>
正如您在评论中提到的,如果您获取的JSON类似于
var obj = {
"PublishDate": "\/Date(1435757849000+0000)\/"
}
并且您无法控制该值(因为您将Date()括在斜杠中),那么您将需要
逃避周围的slashs Date
。
obj.PublishDate.replace(/\\//g, "");
并评估剩余的表达式
eval(obj.PublishDate.replace(/\\//g, ""))
获取实际日期: Wed Jul 08 2015 11:48
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.