Languages
[Edit]
EN

C# / .NET - get system uptime

14 points
Created by:
Wade
562

In C# / .NET it is possible to get system uptime in following way.

Quick solution:

TimeSpan uptime = TimeSpan.FromMilliseconds(Environment.TickCount);

Console.WriteLine($"System time up: " +
	$"{uptime.Days} days " +
	$"{uptime.Hours} hours " +
	$"{uptime.Minutes} minutes " +
	$"{uptime.Seconds} seconds");

// $ - String interpolation was introduced in C# 6

 

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");

// $ - String interpolation was introduced in C# 6

Example 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");

Example 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");

Example output:

System time up: 2 days 9 hours 6 minutes 10 seconds

 

References

  1. Stopwatch.GetTimestamp Method - Microsoft Docs
  2. TimeSpan.FromSeconds Method - Microsoft Docs
  3. Environment.TickCount Property - Microsoft Docs
  4. $ - string interpolation (C# reference) - Microsoft Docs

Alternative titles

  1. C# / .NET - get system up time
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join