C126
C126

Reputation: 31

Finding uptime of a program but showing it in MINUTES

So I run some type of game, and I want to add a command !uptime that displays how long server has been running for since the last open or whatever

This code (from microsoft website) shows the tick count and displays it correctly

        int result = Environment.TickCount & Int32.MaxValue;
        player.SendMessage("Result: " + result);

but I want to be able to display how long its been up in minutes.

Upvotes: 2

Views: 675

Answers (3)

Roujo
Roujo

Reputation: 503

From the MSDN documentation, we can see that Environment.TickCount

Gets the number of milliseconds elapsed since the system started.

You can then convert it to minutes like so:

var minutes = (Environment.TickCount - serverStartTickCount) / 60000; // 1000 ms/s * 60 s/m

Alternatively, you might want to consider storing DateTime.Now when the server starts. Say your class is called Program, you can add this to it:

public static readonly DateTime ServerStartTime = DateTime.Now;

and then do this when the command is run:

var uptime = DateTime.Now - Program.ServerStartTime;
var minutes = uptime.TotalMinutes;

This would allow you to get an accurate uptime when the Environment.TickCount roll over every few weeks, as @Carlos pointed out.

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190897

Use a TimeSpan.

TimeSpan uptime = TimeSpan.FromMilliseconds(Environment.TickCount);
double totalMinutes = uptime.TotalMinutes;

Upvotes: 0

Carlos
Carlos

Reputation: 6021

From the reference docs:

A 32-bit signed integer containing the amount of time in milliseconds that has passed since the last time the computer was started.

So divide by 1000 to get seconds, and then 60 to get minutes.

Note the thing is only 32 bit, so it loops back every few weeks.

Upvotes: 0

Related Questions