EN
C# / .NET - get system up time
14
points
In C# / .NET it is possible to get system up time in following way.
1. Environment.TickCount
property value conversion example
public static class TimeUtils
{
public static TimeSpan GetSystemUpTime()
{
return TimeSpan.FromMilliseconds(Environment.TickCount);
}
}
Example:
TimeSpan time = TimeUtils.GetSystemUpTime();
Console.WriteLine($"System time up: " +
$"{time.Days} days " +
$"{time.Hours} hours " +
$"{time.Minutes} minutes " +
$"{time.Seconds} seconds");
Output:
System time up: 2 days 8 hours 25 minutes 54 seconds
2. Stopwatch.GetTimestamp
method example
public static class TimeUtils
{
public static TimeSpan GetSystemUpTime()
{
double couter = Stopwatch.GetTimestamp();
return TimeSpan.FromSeconds(couter / Stopwatch.Frequency);
}
}
Example:
TimeSpan time = TimeUtils.GetSystemUpTime();
Console.WriteLine($"System time up: " +
$"{time.Days} days " +
$"{time.Hours} hours " +
$"{time.Minutes} minutes " +
$"{time.Seconds} seconds");
Output:
System time up: 2 days 8 hours 53 minutes 54 seconds
3. Environment.TickCount
property value subtraction example
public static class TimeUtils
{
public static TimeSpan GetSystemUpTime()
{
DateTime currentTime = DateTime.Now;
DateTime bootTime = currentTime.AddMilliseconds(-Environment.TickCount);
return currentTime - bootTime;
}
}
Example:
TimeSpan time = TimeUtils.GetSystemUpTime();
Console.WriteLine($"System time up: " +
$"{time.Days} days " +
$"{time.Hours} hours " +
$"{time.Minutes} minutes " +
$"{time.Seconds} seconds");
Output:
System time up: 2 days 9 hours 6 minutes 10 seconds