Get Server Uptime

Started by ., Sep 19, 2015, 06:49 PM

Previous topic - Next topic

.

Someone asked me today how to get the server uptime. And rather then sending this through a PM I chose to post it here. And avoid further similar questions.

Snippet:
// Should be executed at server start up
_START_TIMESTAMP <- time();
// Returns a string with the server uptime
function UptimeToStr()
{
    // Get the uptime
    local s = (time() - _START_TIMESTAMP);
    // Get the days
    local d = (((s/60)/60)/24);
    // Remove the days
    s -= (((d*60)*60)*24);
    // Get the hours
    local h = ((s/60)/60);
    // Remove the hours
    s -= ((h*60)*60);
    // Get the minutes
    local m = (s/60);
    // Remove the minutes
    s -= (m*60);
    // Format the time string
    return ::format(@"%d day%s, %d hour%s, %d minute%s, %d seconds%s",
                    d, (d == 1 ? "": "s"),
                    h, (h == 1 ? "": "s"),
                    m, (m == 1 ? "": "s"),
                    s, (s == 1 ? "": "s")
    );

}

Example:
print(UptimeToStr());
Output should be in the format "# day(s), # hour(s), # minute(s), # seconds(s)". # is the resulted number (obviously)
.

KAKAN

oh no

soulshaker


Thijn

Quote from: soulshaker on Sep 20, 2015, 09:11 AMI use this
That will only work for around 30 days, then the integer will overflow and will return a negative number.
You're not doing anything with the milliseconds as well, so why not use time() instead :)