How can I convert time to decimal number in JavaScript?

后端 未结 4 2244
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-15 17:43

I\'m too lazy to fill out my time sheet at work by the end at the end of every month, so I\'ve started adding some functions to our PDF form. Acrobat Pro offers to make advanced

4条回答
  •  鱼传尺愫
    2021-02-15 18:32

    As alternative, I was curious if this could be done using Date.parse, and it can.

    The following code returns the same values as the selected answer, except for garbage input in which case it returns zero. The 1970 date is used because that is UNIX time zero.

    Note that MDN says, "It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent."

    var test = [undefined, null, "", "garbage", "0", "00:00", "  01:11", "3:44", "2:3", "5.06"];
    var hours = 0;
    var html = "";
    
    for (var i = 0; i < test.length; i++) {
      html += "";
      html += "";
      hours = timeStringToFloat(test[i]);
      html += "";
      hours = timeStringToNumber(test[i]);
      html += "";
      html += "";
      html += "";
    }
    stdout.innerHTML = html;
    
    function timeStringToNumber(time) {
      return ((new Date(("01 Jan 1970 " + time || "").replace(".", ":") + " GMT")) / 3600000) || 0;
    }
    
    function timeStringToFloat(time) {
      try {
        var hoursMinutes = time.split(/[.:]/);
        var hours = parseInt(hoursMinutes[0], 10);
        var minutes = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
        return hours + minutes / 60;
      } catch (e) {
        return "ERROR";
      }
    }
    
    function hoursToString(hours) {
      var minutes = hours * 60;
      return (
        ("00" + Math.floor(minutes / 60)).slice(-2) +
        ":" +
        ("00" + Math.round(minutes % 60)).slice(-2)
      );
    }
    body {
      font-family: sans-serif;
      font-size: 12px;
    }
    
    h4 {
      color: white;
      background-color: steelblue;
      padding: 0.5em;
    }
    
    table {
      border-collapse: collapse;
    }
    
    table td {
      border: 1px solid gray;
      min-height: 1em;
    }

    Test Output:

    Method A is the original and Method B the alternative.
    " + test[i] + "" + hours + "" + hours + "" + hoursToString(hours) + "
    String Method A Method B ToString

    *

    function timeStringToNumber( time ) 
    {
        return ((new Date(("01 Jan 1970 " + time || "").replace(".",":") + " GMT")) / 3600000) || 0;
    }
    

提交回复
热议问题