从API到标准格式的Unix时间

时间:2018-12-27 21:59:09

标签: javascript time

我正在为应用程序https://openweathermap.org/current使用openweathermap,我需要输入当前时间和城市天气。

API以UNIX格式显示的时间。如何以标准格式(h:m:s)在应用程序中输入时间

与API中的日期/时间一致(dt ....数据计算时间,unix,UTC)

在我的JS代码下面

    document.querySelector('#city').addEventListener('keyup', function(e) {
  if (e.keyCode === 13) {

        var city = $(this).val();
        if (city !== '') {

            $.ajax({

                url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
                    "&APPID=bb037310921af67f24ba53f2bad48b1d",
                type: "GET",
                dataType: "json",
                success: function (data) {
                    var widget = show(data);

                    $("#show").html(widget);

                    $("#city").val(' ');

                }

            });

        } else {
            $("#error").html("<div class='alert alert-danger text-center'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>Field cannot be empty</div>");
        }

    };
});


function show(data) {
    return "<h2>Current Weather for " + data.name + "," + data.sys.country + "</h2>" +
    "<h3><strong>Wind Speed</strong>: " + data.dt + "</h3>" +
        "<h3><strong>Weather</strong>: <img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>" + data.weather[0].main + "</h3>" +
        "<h3><strong>Description</strong>: " + data.weather[0].description + "</h3>" +
        "<h3><strong>Temperature</strong>: " + data.main.temp + "&deg;C</h3>" +
        "<h3><strong>Pressure</strong>: " + data.main.pressure + "hPa</h3>" +
        "<h3><strong>Humidity</strong>: " + data.main.humidity + " %</h3>" +
        "<h3><strong>Min. Temperature</strong>: " + data.main.temp_min + "&deg;C</h3>" +
        "<h3><strong>Max. Temperature</strong>: " + data.main.temp_max + "&deg;C</h3>" +
        "<h3><strong>Wind Speed</strong>: " + data.wind.speed + "m/s</h3>" +
        "<h3><strong>Wind Direction</strong>: " + data.wind.deg + "&deg;</h3>";

}

2 个答案:

答案 0 :(得分:1)

如果要让用户以本地格式输入一些日期和时间并获取UNIX时间戳,则可以使用Date.parse(),只是它返回毫秒,而您需要秒,因此将结果除以1000。 (1970年1月1日这两个日期的基本日期和时间都相同。)UTP:

function doConvert(event){
  unix.textContent=Math.round(Date.parse(event.target.value)/1000);
}
<input type="datetime-local" onchange="doConvert(event)"><br>
<div id="unix"></div>

如果您反过来说(UNIX可读时间),请使用Date()(记住将秒转换为毫秒)及其toLocaleString()

function doConvert(event){
  time.textContent=new Date(event.target.valueAsNumber*1000).toLocaleString();
}
<input type="number" oninput="doConvert(event)"><br>
<div id="time"></div>

答案 1 :(得分:0)

UnixTime = https://en.wikipedia.org/wiki/Unix_time

var UnixTime = 1525478400; 
var myDate = new Date(UnixTime*1000);
var HH = myDate.getHours(); 
var MM = myDate.getMinutes();
var SS = myDate.getSeconds();
document.write(HH+":"+MM+":"+SS);