【问题标题】:Javascript/jquery- How to get time closest within an array?Javascript/jquery-如何获取数组中最接近的时间?
【发布时间】:2013-10-11 20:03:11
【问题描述】:

我正在尝试获取数组或列表等中最接近的时间。 我能够找到此代码并尝试通过编辑使其工作,但没有任何运气。 如果它更容易,可以使用jquery。下面只是javascript虽然 如何输出最接近时间 which = thetime 的时间

经过更多研究,我发现了这个 sn-p,并认为它可能对我的事​​业有用:

var date1 = myDate,
date2 = new Date();
return (date1.getTime() < date2.getTime());

我正在尝试什么

var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()

if (minutes < 10) {
    minutes = "0" + minutes
}

var thetime = hours + ":" + minutes + " "

var json = [{
    "times": {
        "times1": "20:01",
        "times2": "21:43",
        "times3": "22:56",
        "times4": "23:21"
    }
}]
var times = [];
var jsontimes = json[0].times;
for (var i in jsontimes) {
    times.push(new Date(jsontimes[i]))
}
times.sort(function (a, b) {
    return Math.abs(thetime - a / new Date()) + Math.abs(thetime - b / new Date())
});

// display code
for (var i = 0; i < jsontimes.length; i++)
    document.getElementById("output").innerHTML += dates[i] + "<br>";

【问题讨论】:

    标签: javascript php jquery json


    【解决方案1】:

    您正在尝试使用无效值(例如“20:01”)创建 Date 对象,从而导致日期无效。根据 MDN,在创建新的 Date 对象时可以通过以下方式传递参数:

    Date(value)
    Date(dateString)
    Date(year, month, day [, hour, minute, second, millisecond])
    

    在哪里 value 是一个“整数值,表示自 1970 年 1 月 1 日 00:00:00 UTC(Unix 纪元)以来的毫秒数。”和

    dateString 是“表示日期的字符串值。字符串应采用解析方法可识别的格式(符合 IETF 的 RFC 2822 时间戳)。”

    您可以在此处阅读更多内容: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

    这并不能真正回答您最初的问题,但它应该可以帮助您创建一个包含所需值的数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      • 2012-10-30
      • 2012-06-11
      相关资源
      最近更新 更多