Work with a time span in Javascript

后端 未结 7 733
感动是毒
感动是毒 2020-11-30 05:53

Using Date.js already, but can also use another library if necessary.

Not sure what is the best way to work with time deltas. Specifically, I want to display the tim

7条回答
  •  北海茫月
    2020-11-30 06:15

    /**
     * 计算时间对象与当前时间的差距,并显示友好的文本 
     * English: Calculating the difference between the given time and the current time and then showing the results.
     */
    function date2Text(date) {
        var milliseconds = new Date() - date;
        var timespan = new TimeSpan(milliseconds);
        if (milliseconds < 0) {
            return timespan.toString() + "之后";
        }else{
            return timespan.toString() + "前";
        }
    }
    
    /**
     * 用于计算时间间隔的对象
     * English: Using a function to calculate the time interval
     * @param milliseconds 毫秒数
     */
    var TimeSpan = function (milliseconds) {
        milliseconds = Math.abs(milliseconds);
        var days = Math.floor(milliseconds / (1000 * 60 * 60 * 24));
        milliseconds -= days * (1000 * 60 * 60 * 24);
    
        var hours = Math.floor(milliseconds / (1000 * 60 * 60));
        milliseconds -= hours * (1000 * 60 * 60);
    
        var mins = Math.floor(milliseconds / (1000 * 60));
        milliseconds -= mins * (1000 * 60);
    
        var seconds = Math.floor(milliseconds / (1000));
        milliseconds -= seconds * (1000);
        return {
            getDays: function () {
                return days;
            },
            getHours: function () {
                return hours;
            },
            getMinuts: function () {
                return mins;
            },
            getSeconds: function () {
                return seconds;
            },
            toString: function () {
                var str = "";
                if (days > 0 || str.length > 0) {
                    str += days + "天";
                }
                if (hours > 0 || str.length > 0) {
                    str += hours + "小时";
                }
                if (mins > 0 || str.length > 0) {
                    str += mins + "分钟";
                }
                if (days == 0 && (seconds > 0 || str.length > 0)) {
                    str += seconds + "秒";
                }
                return str;
            }
        }
    }
    

提交回复
热议问题