【问题标题】:How to convert timestamp into days in javascript?如何在javascript中将时间戳转换为天数?
【发布时间】:2020-07-09 10:31:48
【问题描述】:

我得到 endtimestamp 作为 api 响应,我想从当前时间戳计算天数。我已经为此转换编写了一个函数,但给了我磨损的结果。

function timeDifference(current, previous) {

        var msPerMinute = 60 * 1000;
        var msPerHour = msPerMinute * 60;
        var msPerDay = msPerHour * 24;
        var msPerMonth = msPerDay * 30;
        var msPerYear = msPerDay * 365;
    
        var elapsed = current - previous;
    
        if (elapsed < msPerMinute) {
             return Math.round(elapsed/1000) + ' seconds ago';   
        }
    
        else if (elapsed < msPerHour) {
             return Math.round(elapsed/msPerMinute) + ' minutes ago';   
        }
    
        else if (elapsed < msPerDay ) {
             return Math.round(elapsed/msPerHour ) + ' hours ago';   
        }
    
        else if (elapsed < msPerMonth) {
            return '' + Math.round(elapsed/msPerDay) + ' days ago';   
        }
    
        else if (elapsed < msPerYear) {
            return '' + Math.round(elapsed/msPerMonth) + ' months ago';   
        }
    
        else {
            return '' + Math.round(elapsed/msPerYear ) + ' years ago';   
        }
    }

请建议我正确的解决方案,以便我可以得到正确的转换

【问题讨论】:

  • 考虑附加示例输入和您期望的相应输出。

标签: javascript timestamp


【解决方案1】:

我建议使用一个库作为 moment.js https://momentjs.com/docs/#/displaying/difference/ 除了更容易编码之外,您不会遇到闰年、闰秒等问题。

【讨论】:

    【解决方案2】:
    function timeDifference(date) {
        var seconds = Math.floor((new Date() - date) / 1000);
        if(Math.round(seconds/(60*60*24*365.25)) >= 2) return Math.round(seconds/(60*60*24*365.25)) + " years ago";
        else if(Math.round(seconds/(60*60*24*365.25)) >= 1) return "1 year ago";
        else if(Math.round(seconds/(60*60*24*30.4)) >= 2) return Math.round(seconds/(60*60*24*30.4)) + " months ago";
        else if(Math.round(seconds/(60*60*24*30.4)) >= 1) return "1 month ago";
        else if(Math.round(seconds/(60*60*24*7)) >= 2) return Math.round(seconds/(60*60*24*7)) + " weeks ago";
        else if(Math.round(seconds/(60*60*24*7)) >= 1) return "1 week ago";
        else if(Math.round(seconds/(60*60*24)) >= 2) return Math.round(seconds/(60*60*24)) + " days ago";
        else if(Math.round(seconds/(60*60*24)) >= 1) return "1 day ago";
        else if(Math.round(seconds/(60*60)) >= 2) return Math.round(seconds/(60*60)) + " hours ago";
        else if(Math.round(seconds/(60*60)) >= 1) return "1 hour ago";
        else if(Math.round(seconds/60) >= 2) return Math.round(seconds/60) + " minutes ago";
        else if(Math.round(seconds/60) >= 1) return "1 minute ago";
        else if(seconds >= 2)return seconds + " seconds ago";
        else return seconds + "1 second ago";
    }
    

    你也可以使用这个插件javascript-time-ago

    【讨论】:

      【解决方案3】:

      我喜欢减少东西,这是我的解决方案。

      /**
       * @method msToTimeString : convert milliseconds to time string
       * @param {number} ms : milliseconds to convert
       */
      const msToTimeString = ms => {
          const mods = [1000, 60, 60, 24, 365]; // time modulus
          const names = ["millisecond", "second", "minute", "hour", "day"]; // names
          return mods.reduce((acc, cur, index) => { // reduce modulus
              let unit = acc.val % cur; // calc current time scale
              acc.val = (acc.val - unit) / cur; // keep remaining
              acc[names[index]] = unit; // assign name to result
              return acc; // next
          }, {val: ms});
      };
      
      let past = new Date("2020-03-17T00:00:00").getTime(), // past date
          now = Date.now(); // now
          
      let calc = msToTimeString(now - past);
      console.log(calc.day, "days", calc.hour, "hours"); // also : calc.minute, calc.second, calc.millisecond

      相同的代码,野蛮的一行

      /**
       * @method msToTimeString : convert milliseconds to time string
       * @param {number} ms : milliseconds to convert
       */
      const msToTimeString = ms => {
          const names = ["millisecond", "second", "minute", "hour", "day"]; // names
          return [1000, 60, 60, 24, 365].reduce((acc, cur, index) => ({...acc, [names[index]]: acc.val % cur, val: (acc.val - (acc.val % cur)) / cur}), {val: ms});
      };
      
      let past = new Date("2020-03-17T00:00:00").getTime(), // past date
          now = Date.now(); // now
          
      console.log(msToTimeString(now - past)); // display !

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-05
        • 2013-02-08
        • 2021-11-08
        • 2010-10-25
        相关资源
        最近更新 更多