如何将毫秒转换为人类可读的形式?

时间:2008-10-06 18:23:25

标签: date time string-formatting datetime-format

我需要将任意数量的毫秒转换为Days,Hours,Minutes Second。

例如:10天,5小时,13分钟,1秒。

21 个答案:

答案 0 :(得分:221)

好吧,因为没有其他人加强,我会编写简单的代码来执行此操作:

x = ms / 1000
seconds = x % 60
x /= 60
minutes = x % 60
x /= 60
hours = x % 24
x /= 24
days = x

我很高兴你在几天停下来并没有问几个月。 :)

注意,在上文中,假设/表示截断整数除法。如果以/表示浮点除法的语言使用此代码,则需要根据需要手动截断除法的结果。

答案 1 :(得分:56)

设A为毫秒数。然后你有:

seconds=(A/1000)%60
minutes=(A/(1000*60))%60
hours=(A/(1000*60*60))%24

等等(%是模数运算符)。

希望这有帮助。

答案 2 :(得分:24)

下面的两个解决方案都使用 javascript (我不知道解决方案是语言无关的!)。如果捕获持续时间> 1 month,则需要扩展这两种解决方案。

解决方案1:使用Date对象

var date = new Date(536643021);
var str = '';
str += date.getUTCDate()-1 + " days, ";
str += date.getUTCHours() + " hours, ";
str += date.getUTCMinutes() + " minutes, ";
str += date.getUTCSeconds() + " seconds, ";
str += date.getUTCMilliseconds() + " millis";
console.log(str);

给出:

"6 days, 5 hours, 4 minutes, 3 seconds, 21 millis"

图书馆很有用,但为什么在你可以重新发明轮子时使用图书馆呢! :)

解决方案2:编写自己的解析器

var getDuration = function(millis){
    var dur = {};
    var units = [
        {label:"millis",    mod:1000},
        {label:"seconds",   mod:60},
        {label:"minutes",   mod:60},
        {label:"hours",     mod:24},
        {label:"days",      mod:31}
    ];
    // calculate the individual unit values...
    units.forEach(function(u){
        millis = (millis - (dur[u.label] = (millis % u.mod))) / u.mod;
    });
    // convert object to a string representation...
    var nonZero = function(u){ return dur[u.label]; };
    dur.toString = function(){
        return units
            .reverse()
            .filter(nonZero)
            .map(function(u){
                return dur[u.label] + " " + (dur[u.label]==1?u.label.slice(0,-1):u.label);
            })
            .join(', ');
    };
    return dur;
};

使用您需要的任何字段创建“持续时间”对象。 格式化时间戳然后变得简单......

console.log(getDuration(536643021).toString());

给出:

"6 days, 5 hours, 4 minutes, 3 seconds, 21 millis"

答案 3 :(得分:20)

Apache Commons Lang有一个DurationFormatUtils,其中包含非常有用的方法,例如formatDurationWords

答案 4 :(得分:7)

你应该使用你正在使用的任何语言的日期时间函数,但是,这里只是为了好玩的代码:

int milliseconds = someNumber;

int seconds = milliseconds / 1000;

int minutes = seconds / 60;

seconds %= 60;

int hours = minutes / 60;

minutes %= 60;

int days = hours / 24;

hours %= 24;

答案 5 :(得分:4)

function convertTime(time) {        
    var millis= time % 1000;
    time = parseInt(time/1000);
    var seconds = time % 60;
    time = parseInt(time/60);
    var minutes = time % 60;
    time = parseInt(time/60);
    var hours = time % 24;
    var out = "";
    if(hours && hours > 0) out += hours + " " + ((hours == 1)?"hr":"hrs") + " ";
    if(minutes && minutes > 0) out += minutes + " " + ((minutes == 1)?"min":"mins") + " ";
    if(seconds && seconds > 0) out += seconds + " " + ((seconds == 1)?"sec":"secs") + " ";
    if(millis&& millis> 0) out += millis+ " " + ((millis== 1)?"msec":"msecs") + " ";
    return out.trim();
}

答案 6 :(得分:4)

这是我写的一种方法。它需要integer milliseconds value并返回human-readable String

public String convertMS(int ms) {
    int seconds = (int) ((ms / 1000) % 60);
    int minutes = (int) (((ms / 1000) / 60) % 60);
    int hours = (int) ((((ms / 1000) / 60) / 60) % 24);

    String sec, min, hrs;
    if(seconds<10)  sec="0"+seconds;
    else            sec= ""+seconds;
    if(minutes<10)  min="0"+minutes;
    else            min= ""+minutes;
    if(hours<10)    hrs="0"+hours;
    else            hrs= ""+hours;

    if(hours == 0)  return min+":"+sec;
    else    return hrs+":"+min+":"+sec;

}

答案 7 :(得分:2)

Long serverUptimeSeconds = 
    (System.currentTimeMillis() - SINCE_TIME_IN_MILLISECONDS) / 1000;


String serverUptimeText = 
String.format("%d days %d hours %d minutes %d seconds",
serverUptimeSeconds / 86400,
( serverUptimeSeconds % 86400) / 3600 ,
((serverUptimeSeconds % 86400) % 3600 ) / 60,
((serverUptimeSeconds % 86400) % 3600 ) % 60
);

答案 8 :(得分:2)

您的选择很简单:

  1. 编写代码进行转换(即除以milliSecondsPerDay得到天数,并使用模数除以milliSecondsPerHour得到小时,并使用模数除以milliSecondsPerMinute并除以1000秒.milliSecondsPerMinute = 60000,milliSecondsPerHour = 60 * milliSecondsPerMinute,milliSecondsPerDay = 24 * milliSecondsPerHour。
  2. 使用某种操作程序。 UNIX和Windows都具有可以从Ticks或second类型值获得的结构。

答案 9 :(得分:2)

我建议使用您选择的语言/框架提供的日期/时间函数/库。还要检查字符串格式化函数,因为它们通常提供简单的方法来传递日期/时间戳并输出人类可读的字符串格式。

答案 10 :(得分:2)

Long expireTime = 69l;
Long tempParam = 0l;

Long seconds = math.mod(expireTime, 60);
tempParam = expireTime - seconds;
expireTime = tempParam/60;
Long minutes = math.mod(expireTime, 60);
tempParam = expireTime - minutes;
expireTime = expireTime/60;
Long hours = math.mod(expireTime, 24);
tempParam = expireTime - hours;
expireTime = expireTime/24;
Long days = math.mod(expireTime, 30);

system.debug(days + '.' + hours + ':' + minutes + ':' + seconds);

这应该打印:0.0:1:9

答案 11 :(得分:2)

为什么不做这样的事情:

var ms = 86400;

var seconds = ms / 1000; //86.4

var minutes = seconds / 60; //1.4400000000000002

var hours = minutes / 60; //0.024000000000000004

var days = hours / 24; //0.0010000000000000002

处理浮点精度,例如编号(minutes.toFixed(5))// 1.44

答案 12 :(得分:2)

在java中

public static String formatMs(long millis) {
    long hours = TimeUnit.MILLISECONDS.toHours(millis);
    long mins = TimeUnit.MILLISECONDS.toMinutes(millis);
    long secs = TimeUnit.MILLISECONDS.toSeconds(millis);
    return String.format("%dh %d min, %d sec",
            hours,
            mins - TimeUnit.HOURS.toMinutes(hours),
            secs - TimeUnit.MINUTES.toSeconds(mins)
    );
}

给出这样的东西:

12h 1 min, 34 sec

答案 13 :(得分:1)

我无法评论你的问题的第一个答案,但是有一个小错误。您应该使用parseInt或Math.floor将浮点数转换为整数,i

var days, hours, minutes, seconds, x;
x = ms / 1000;
seconds = Math.floor(x % 60);
x /= 60;
minutes = Math.floor(x % 60);
x /= 60;
hours = Math.floor(x % 24);
x /= 24;
days = Math.floor(x);

就个人而言,我在我的项目中使用CoffeeScript,我的代码看起来像这样:

getFormattedTime : (ms)->
        x = ms / 1000
        seconds = Math.floor x % 60
        x /= 60
        minutes = Math.floor x % 60
        x /= 60
        hours = Math.floor x % 24
        x /= 24
        days = Math.floor x
        formattedTime = "#{seconds}s"
        if minutes then formattedTime = "#{minutes}m " + formattedTime
        if hours then formattedTime = "#{hours}h " + formattedTime
        formattedTime 

答案 14 :(得分:1)

这是一个解决方案。稍后您可以通过“:”拆分并获取数组的值

/**
 * Converts milliseconds to human readeable language separated by ":"
 * Example: 190980000 --> 2:05:3 --> 2days 5hours 3min
 */
function dhm(t){
    var cd = 24 * 60 * 60 * 1000,
        ch = 60 * 60 * 1000,
        d = Math.floor(t / cd),
        h = '0' + Math.floor( (t - d * cd) / ch),
        m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
    return [d, h.substr(-2), m.substr(-2)].join(':');
}

var delay = 190980000;                   
var fullTime = dhm(delay);
console.log(fullTime);

答案 15 :(得分:1)

这是我使用TimeUnit的解决方案。

更新:我应该指出这是用groovy编写的,但Java几乎完全相同。

def remainingStr = ""

/* Days */
int days = MILLISECONDS.toDays(remainingTime) as int
remainingStr += (days == 1) ? '1 Day : ' : "${days} Days : "
remainingTime -= DAYS.toMillis(days)

/* Hours */
int hours = MILLISECONDS.toHours(remainingTime) as int
remainingStr += (hours == 1) ? '1 Hour : ' : "${hours} Hours : "
remainingTime -= HOURS.toMillis(hours)

/* Minutes */
int minutes = MILLISECONDS.toMinutes(remainingTime) as int
remainingStr += (minutes == 1) ? '1 Minute : ' : "${minutes} Minutes : "
remainingTime -= MINUTES.toMillis(minutes)

/* Seconds */
int seconds = MILLISECONDS.toSeconds(remainingTime) as int
remainingStr += (seconds == 1) ? '1 Second' : "${seconds} Seconds"

答案 16 :(得分:1)

灵活的方式:
(不是针对当前日期而是针对持续时间做得足够好)

/**
convert duration to a ms/sec/min/hour/day/week array
@param {int}        msTime              : time in milliseconds 
@param {bool}       fillEmpty(optional) : fill array values even when they are 0.
@param {string[]}   suffixes(optional)  : add suffixes to returned values.
                                        values are filled with missings '0'
@return {int[]/string[]} : time values from higher to lower(ms) range.
*/
var msToTimeList=function(msTime,fillEmpty,suffixes){
    suffixes=(suffixes instanceof Array)?suffixes:[];   //suffixes is optional
    var timeSteps=[1000,60,60,24,7];    // time ranges : ms/sec/min/hour/day/week
    timeSteps.push(1000000);    //add very big time at the end to stop cutting
    var result=[];
    for(var i=0;(msTime>0||i<1||fillEmpty)&&i<timeSteps.length;i++){
        var timerange = msTime%timeSteps[i];
        if(typeof(suffixes[i])=="string"){
            timerange+=suffixes[i]; // add suffix (converting )
            // and fill zeros :
            while(  i<timeSteps.length-1 &&
                    timerange.length<((timeSteps[i]-1)+suffixes[i]).length  )
                timerange="0"+timerange;
        }
        result.unshift(timerange);  // stack time range from higher to lower
        msTime = Math.floor(msTime/timeSteps[i]);
    }
    return result;
};

注意:如果要控制时间范围,也可以将 timeSteps 设置为参数。

如何使用(复制测试):

var elsapsed = Math.floor(Math.random()*3000000000);

console.log(    "elsapsed (labels) = "+
        msToTimeList(elsapsed,false,["ms","sec","min","h","days","weeks"]).join("/")    );

console.log(    "half hour : "+msToTimeList(elsapsed,true)[3]<30?"first":"second"   );

console.log(    "elsapsed (classic) = "+
        msToTimeList(elsapsed,false,["","","","","",""]).join(" : ")    );

答案 17 :(得分:1)

我建议使用http://www.ocpsoft.org/prettytime/库..

以人类可读的形式获得时间间隔非常简单,如

PrettyTime p = new PrettyTime(); System.out.println(p.format(new Date()));

它会打印出“从现在开始的时刻”

其他例子

PrettyTime p = new PrettyTime()); Date d = new Date(System.currentTimeMillis()); d.setHours(d.getHours() - 1); String ago = p.format(d);

then string ago =“1小时前”

答案 18 :(得分:0)

这是JAVA中更精确的方法,我已经实现了这个简单的逻辑,希望这会对你有所帮助:

    public String getDuration(String _currentTimemilliSecond)
    {
        long _currentTimeMiles = 1;         
        int x = 0;
        int seconds = 0;
        int minutes = 0;
        int hours = 0;
        int days = 0;
        int month = 0;
        int year = 0;

        try 
        {
            _currentTimeMiles = Long.parseLong(_currentTimemilliSecond);
            /**  x in seconds **/   
            x = (int) (_currentTimeMiles / 1000) ; 
            seconds = x ;

            if(seconds >59)
            {
                minutes = seconds/60 ;

                if(minutes > 59)
                {
                    hours = minutes/60;

                    if(hours > 23)
                    {
                        days = hours/24 ;

                        if(days > 30)
                        {
                            month = days/30;

                            if(month > 11)
                            {
                                year = month/12;

                                Log.d("Year", year);
                                Log.d("Month", month%12);
                                Log.d("Days", days % 30);
                                Log.d("hours ", hours % 24);
                                Log.d("Minutes ", minutes % 60);
                                Log.d("Seconds  ", seconds % 60);   

                                return "Year "+year + " Month "+month%12 +" Days " +days%30 +" hours "+hours%24 +" Minutes "+minutes %60+" Seconds "+seconds%60;
                            }
                            else
                            {
                                Log.d("Month", month);
                                Log.d("Days", days % 30);
                                Log.d("hours ", hours % 24);
                                Log.d("Minutes ", minutes % 60);
                                Log.d("Seconds  ", seconds % 60);   

                                return "Month "+month +" Days " +days%30 +" hours "+hours%24 +" Minutes "+minutes %60+" Seconds "+seconds%60;
                            }

                        }
                        else
                        {
                            Log.d("Days", days );
                            Log.d("hours ", hours % 24);
                            Log.d("Minutes ", minutes % 60);
                            Log.d("Seconds  ", seconds % 60);   

                            return "Days " +days +" hours "+hours%24 +" Minutes "+minutes %60+" Seconds "+seconds%60;
                        }

                    }
                    else
                    {
                        Log.d("hours ", hours);
                        Log.d("Minutes ", minutes % 60);
                        Log.d("Seconds  ", seconds % 60);

                        return "hours "+hours+" Minutes "+minutes %60+" Seconds "+seconds%60;
                    }
                }
                else
                {
                    Log.d("Minutes ", minutes);
                    Log.d("Seconds  ", seconds % 60);

                    return "Minutes "+minutes +" Seconds "+seconds%60;
                }
            }
            else
            {
                Log.d("Seconds ", x);
                return " Seconds "+seconds;
            }
        }
        catch (Exception e) 
        {
            Log.e(getClass().getName().toString(), e.toString());
        }
        return "";
    }

    private Class Log
    {
        public static void d(String tag , int value)
        {
            System.out.println("##### [ Debug ]  ## "+tag +" :: "+value);
        }
    }

答案 19 :(得分:0)

使用awk的解决方案:

$ ms=10000001; awk -v ms=$ms 'BEGIN {x=ms/1000; 
                                     s=x%60; x/=60;
                                     m=x%60; x/=60;
                                     h=x%60;
                              printf("%02d:%02d:%02d.%03d\n", h, m, s, ms%1000)}'
02:46:40.001

答案 20 :(得分:0)

在python 3中,您可以使用以下代码段实现目标:

from datetime import timedelta

ms = 536643021
td = timedelta(milliseconds=ms)

print(str(td))
# --> 6 days, 5:04:03.021000

Timedelta文档:https://docs.python.org/3/library/datetime.html#datetime.timedelta

timedelta str的__str__方法的来源:https://github.com/python/cpython/blob/33922cb0aa0c81ebff91ab4e938a58dfec2acf19/Lib/datetime.py#L607