2

I am right now making a Discord bot command for runtime, I was wondering what the most compacted (and still correct) way of doing an runtime to catch how long the bot has actually been online and return it in 24hr format.

André
  • 4,417
  • 4
  • 29
  • 56
Persik
  • 275
  • 3
  • 11
  • 20
  • Make a global variable, store Date.now() in it when the bot is started and subtract it from Date.now() in the command, then you'll have milliseconds. Then [convert that](https://stackoverflow.com/questions/10874048/from-milliseconds-to-hour-minutes-seconds-and-milliseconds). – LW001 Apr 19 '18 at 05:38

3 Answers3

14

You don't need to manually save when the bot started. You can use client.uptime and you will get how many milliseconds the bot is up.

From there you can do something like this:

let totalSeconds = (client.uptime / 1000);
let days = Math.floor(totalSeconds / 86400);
totalSeconds %= 86400;
let hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
let minutes = Math.floor(totalSeconds / 60);
let seconds = Math.floor(totalSeconds % 60);

Then you'll have days, hours, minutes and seconds ready to use.

let uptime = `${days} days, ${hours} hours, ${minutes} minutes and ${seconds} seconds`;
André
  • 4,417
  • 4
  • 29
  • 56
2

Here's a very simple solution that returns a human-readable string. It uses the pretty-ms module.

const prettyMilliseconds = require("pretty-ms");
message.channel.send(`Uptime: ${prettyMilliseconds(client.uptime)}`)
// 15d 11h 23m 20s
Beatso
  • 75
  • 1
  • 9
  • 1
    Personally, I have used this solution in many projects before, this is a highly underrated answer. – Johnty Feb 18 '22 at 12:27
1

Much better solution

const moment = require("moment");
require("moment-duration-format");
const duration = moment.duration(client.uptime).format(" D [days], H [hrs], m [mins], s [secs]");

console.log(duration);

//Output = 1 hr, 16 mins, 8 secs
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
ETHYT
  • 63
  • 1
  • 10