如何从日期数组中获取平均时间?

Par*_*ner 1 javascript math date unix-timestamp underscore.js

我正在尝试为 xml 站点地图生成“changefreq”。每次保存页面时,我都会向“save_history”数组添加一个日期,该数组为我提供了要使用的日期列表。最初我以为我只需将所有日期相加并除以长度即可,但这只是给出了自 1970 年 1 月 1 日以来的平均时间。如何修复此函数以获得日期之间的平均时间?

http://jsfiddle.net/jwerre/pAfdM/19/

或者

  getChangeFequency = function(history) {

    var sum = _.reduce(history, function(memo, num) {
      return memo + num.getTime();
    }, 0);
    var average = sum / history.length;
    var hours = average / 3600000;

    console.log("totals:", sum, average, hours); // 20292433147523 1352828876501.5334 375785.7990282037

    if (hours > 17532) {
      return "never";
    } else if ((8766 < hours && hours > 17531)) {
      return "yearly";
    } else if ((730 < hours && hours > 8765)) {
      return "monthly";
    } else if ((168 < hours && hours > 729)) {
      return "weekly";
    } else if ((24 < hours && hours > 167)) {
      return "daily";
    } else if ((1 < hours && hours > 23)) {
      return "hourly";
    } else {
      return "always";
    }
  };

  save_history = [ Tue Nov 13 2012 09:47:39 GMT-0800 (PST), Tue Nov 13 2012 09:47:44 GMT-0800 (PST), Tue Nov 13 2012 09:47:45 GMT-0800 (PST), Tue Nov 13 2012 09:47:46 GMT-0800 (PST), Tue Nov 13 2012 09:47:47 GMT-0800 (PST) ]

  getChangeFrequency(save_history)
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 5

如何修复此函数以获得日期之间的平均时间?

由于您的历史记录是日期的排序数组,因此可以轻松计算平均时间跨度:

(_.last(history) - history[0]) / (history.length - 1)
Run Code Online (Sandbox Code Playgroud)

这在数学上相当于构建一系列间隔并对它们求平均值。结果以毫秒为单位。