我如何返回process.uptime();从毫秒到人类可读的格式?

时间:2017-02-22 23:30:09

标签: javascript node.js discord

我正在制作一部不和谐机器人。我试过这个 -

bot.on('message', message => {
if (message.content === '!uptime') {
    var time = process.uptime();

    function dhm(ms) {
        days = Math.floor(ms / (24 * 60 * 60 * 1000));
        daysms = ms % (24 * 60 * 60 * 1000);
        hours = Math.floor((daysms) / (60 * 60 * 1000));
        hoursms = ms % (60 * 60 * 1000);
        minutes = Math.floor((hoursms) / (60 * 1000));
        minutesms = ms % (60 * 1000);
        sec = Math.floor((minutesms) / (1000));
        return days + ":" + hours + ":" + minutes + ":" + sec;
    }
    message.channel.sendMessage(dhm(time));
   }
});

在聊天中,返回 - 0:0:0:0

// Uptime
bot.on('message', message => {
 if (message.content === '!uptime') {
    var time = process.uptime();
function dhm(t){
var cd = 24 * 60 * 60 * 1000,
    ch = 60 * 60 * 1000,
    d = Math.floor(t / cd),
    h = Math.floor( (t - d * cd) / ch),
    m = Math.round( (t - d * cd - h * ch) / 60000),
    pad = function(n){ return n < 10 ? '0' + n : n; };
  if( m === 60 ){
h++;
m = 0;
  }
  if( h === 24 ){
d++;
h = 0;
  }
  return [d, pad(h), pad(m)].join(':');
}
  message.channel.sendMessage(dhm(time)); 
 }});

这会返回0:00:00

我正在尝试将process.uptime();的值转换为天,小时,分钟和秒。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

顺便说一句,给出的第一条评论不是100%正确。根据最新文档,返回值包括几分之一秒。 Math.floor()应该用于获取整秒。因此,为了获得以毫秒为单位的正常运行时间,需要将process.uptime()值乘以1000。下面的代码示例可能会做您想要的。由于该示例使用了不同的格式,因此您可能需要使代码适应您喜欢的格式,该格式应该简单明了。

您可以在repl.it上试用此代码的变体形式

var uptime = process.uptime();
console.log("Uptime raw:", uptime)
const date = new Date(uptime*1000);
const days = date.getUTCDate() - 1,
      hours = date.getUTCHours(),
      minutes = date.getUTCMinutes(),
      seconds = date.getUTCSeconds(),
      milliseconds = date.getUTCMilliseconds();


let segments = [];

if (days > 0) segments.push(days + ' day' + ((days == 1) ? '' : 's'));
if (hours > 0) segments.push(hours + ' hour' + ((hours == 1) ? '' : 's'));
if (minutes > 0) segments.push(minutes + ' minute' + ((minutes == 1) ? '' : 's'));
if (seconds > 0) segments.push(seconds + ' second' + ((seconds == 1) ? '' : 's'));
if (milliseconds > 0) segments.push(milliseconds + ' millisecond' + ((seconds == 1) ? '' : 's'));
const dateString = segments.join(', ');

console.log("Uptime: " + dateString);