在javascript中添加时间

时间:2011-11-04 20:38:59

标签: javascript regex lisp elisp

前段时间,我发布了question如何在emacs-buffer中添加时间。现在在ikiwiki页面上显示相同的内容。因此,添加的时间是在应该显示添加时间的页面上。也许最好的方法是在javascript中使用该功能。所以我的问题是,如果有人可以将我的elisp问题的答案翻译成javascript。 elisp代码是:

  (defun add-times ()                 
  (interactive)                                
  (let ((minutes 0) (seconds 0))     
    (save-excursion                        
      (goto-char (point-min))
      (while (re-search-forward "\\([0-9]+\\)'\\('\\)?" (point-max) t)
        (if (match-string 2)
            (setq seconds (+ seconds (string-to-number (match-string 1))))
          (setq minutes (+ minutes (string-to-number (match-string 1)))))))
    (insert (format "%d'%d''"(+ minutes (/ seconds 60)) (% seconds 60)))))

1 个答案:

答案 0 :(得分:2)

此?

var seconds = function (str) {
    var m = /\d+(?=')/.exec(str);
    var s = /\d+(?=")/.exec(str);
    return (s ? parseInt(s[0], 10)      : 0) +
           (m ? parseInt(m[0], 10) * 60 : 0);
}

var totalTime = function (strs) {
    var totalSecs = strs.reduce(function (total, str) {
        return seconds(str) + total;
    }, 0);
    var m = Math.floor(totalSecs / 60);
    var s = totalSecs - (m * 60);
    return (m ? m + "'"  : "") +
           (s ? s + "\"" : "");
}

totalTime(["5'30\"", "6'15\"", "10'", "1\""]) // 21'46"