Languages
[Edit]
EN

C# / .NET - get system up time

14 points
Created by:
JustMike
3494

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

4. References

  1. Stopwatch.GetTimestamp Method - Microsoft Docs
  2. TimeSpan.FromSeconds Method - Microsoft Docs
  3. Environment.TickCount Property - Microsoft docs
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.