我试图编写一个json脚本来检索最近的最新地震。这很好。
我无法尝试格式化日期和时间。同样对于幅度和深度线,我只需要前3个字符(数字)。 可以在此处找到示例页面:https://www.feildingweather.com/quakes/
我的代码如下:
$(document).ready(function() {
returnQuakes(4);
});
function returnNews() {
var url = 'https://api.geonet.org.nz/news/geonet';
$.getJSON(url, function(data) {
var items = [];
$.each(data.feed, function(key, val) {
items.push("<li>" + "<a target='_blank' " + "href='" + val.link + "'>" + val.title + "</a>" + "</li>");
});
$("<ul/>", {
"class": "list",
html: items.join("")
}).appendTo("#news");
});
}
function returnQuakes(greaterThan) {
var url = 'https://api.geonet.org.nz/quake?MMI=' + greaterThan;
$.getJSON(url, function(data) {
var items = [];
$.each(data.features, function(key, val) {
var dateTime = new Date(Date.parse(val.properties.time));
console.log(dateTime.getDate() + "/" + dateTime.getMonth() + "/" + dateTime.getFullYear() + " " + dateTime.getHours());
items.push("<li class='title'>" +
val.properties.locality +
"<ul>" +
"<li>Magnitude: " + val.properties.magnitude + "</li>" +
"<li>Depth: " + val.properties.depth + "</li>" +
"<li>Time: " + val.properties.time + "</li>" +
"</ul></li>");
});
$("<ul/>", {
"class": "list",
html: items.join("")
}).appendTo("#quakes");
});
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quakes"></div>
&#13;
答案 0 :(得分:0)
似乎一切都运转良好,其中一些细微差别可以通过阅读一些文档来解决
要将date格式化为day/month/year
,您可以使用日期执行以下操作。toLocaleString
var date = new Date();
// I guessed en-GB for your locale
var formatted = date.toLocaleString('en-GB', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: true
})
console.log(formatted)
&#13;
要将您的幅度和深度四舍五入为2位小数,您可以使用toFixed(2)。注意:请记住toFixed返回string
。
var depth = 11.95286655
var magnitude = 4.00689878;
console.log(`Depth: ${depth.toFixed(2)}
Magnitude: ${magnitude.toFixed(2)}`);
&#13;