从 Json 返回的日期如下所示:
2017-09-14T22:11:05.5303556
我希望它以用户友好的格式返回,例如:
2017年9月14日22:11:05
这是 Json:
[
{
id: 98,
dateCreated: "2017-09-14T22:11:05.5303556"
},
{
id: 99,
dateCreated: "2017-09-14T22:11:05.5615556"
}
]
这是 JavaScript:
<script>
$.ajax({
url:'http://mywebsite/api/Response',
dataType: 'json',
success: function(json) {
myTable = $('#myTable').columns({
data:json,
schema: [
{"header":"ID", "key":"id"},
{"header":"Date", "key":"dateCreated"}
],
});
}
});
</script>
我需要进行哪些更改才能以用户友好的格式显示日期?感谢您的帮助。
最佳答案
您可能想查看10 ways to format time and date using javascript .
例如,您可以对每个日期执行类似的操作:
var example_date = '2017-09-14T22:11:05.5303556';
function formatDate(date) {
var d = new Date(date),
month = d.getMonth(),
date = d.getDate(),
year = d.getFullYear(),
hours = ('0' + d.getHours()).slice(-2),
minutes = ('0' + d.getMinutes()).slice(-2),
seconds = ('0' + d.getSeconds()).slice(-2);
month++;
return (month + '/' + date +'/' + year + ' ' + hours + ':' + minutes + ':' + seconds);
}
console.log(formatDate(example_date));
您还可以使用 .toLocaleTimeString()
和 .toLocaleDateString()
并将两者结合起来。
如果您不反对使用第 3 方库,我建议您查看 MomentJS 。它非常擅长让您轻松格式化日期/时间,例如...
for (var i in json){
json[i].dateCreated = moment(json[i].dateCreated).format('MM/DD/YYYY hh/mm/ss');
}
...其中 json
是返回的对象,将生成:
[{"id":98,"dateCreated":"09/14/2017 10/11/05"},{"id":99,"dateCreated":"09/14/2017 10/11/05"}]
关于javascript - 格式化Json返回的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46244350/