V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
Jafy

如何把时间长度(秒)转换成可读的形式

  •  
  •   Jafy · Oct 21, 2015 · 2202 views
    This topic created in 3840 days ago, the information mentioned may be changed or developed.

    像这样写有没有什么问题?

    function getDuration(lasttime) {
        var seconds = ( Date.now() / 1000 | 0 ) - lasttime;
        if (seconds > 60*2) {
            if (seconds > 3600*2) {
                if (seconds > 3600*24*2) {
                    if (seconds > 3600*24*7*2) {
                        if (seconds > 3600*24*30*2) {
                            if (seconds > 3600*24*365*2) {
                                return (seconds / (3600*24*365) | 0) + " years";
                            }
                            return (seconds / (3600*24*30) | 0) + " months";
                        }
                        return (seconds / (3600*24*7) | 0) + " weeks";
                    }
                    return (seconds / (3600*24) | 0) + " days";
                }
                return (seconds / 3600 | 0) + " hours";
            }
            return (seconds / 60 | 0) + " minutes";
        }
        return (seconds) + " seconds";
    }
    
    ryd994
        1
    ryd994  
       Oct 21, 2015
    那为什么不反过来?
    这么多层嵌套真是药丸,多一行少一行看不出来
    if time>year
    return ...
    if time>month
    return ...

    |0 是什么意思?

    另外时间的显示 python 标准库里似乎是有现成的
    tomwan
        2
    tomwan  
       Oct 21, 2015
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3468 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 77ms · UTC 10:53 · PVG 18:53 · LAX 03:53 · JFK 06:53
    ♥ Do have faith in what you're doing.