Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

C# / .NET - get system up time

0 contributions
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

4. References

  1. Stopwatch.GetTimestamp Method - Microsoft Docs
  2. TimeSpan.FromSeconds Method - Microsoft Docs
  3. Environment.TickCount Property - Microsoft docs
0 contributions

Suggested wiki articles:

Suggested findings

Let's do the work and have some fun
  • Dirask is online IT community for professionals and hobbyist 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,
    we will help you. 👍 ✔ 🦄
Read more