Languages
[Edit]
EN

C# / .NET - get system up time

14 points
Created by:
JustMike
26120

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
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join