Languages
[Edit]
EN

C# / .NET - get current machine time in seconds

10 points
Created by:
JustMike
26120

C# / .NET it is possible to take machine time in seconds in following way.

Getting second time with Stopwatch.GetTimestamp method example

public static class TimeUtils
{
	public static long GetSeconds()
	{
		double timestamp = Stopwatch.GetTimestamp();
		double seconds = timestamp / Stopwatch.Frequency;

		return (long)seconds;
	}
}

Example:

long t1 = TimeUtils.GetSeconds();

Thread.Sleep(1000);

long t2 = TimeUtils.GetSeconds();
long dt = t2 - t1;

Console.WriteLine(t2 + " - " + t1 + " = " + dt + " s");

Output:

200206 - 200205 = 1 s
Notes: 
  • Stopwatch.GetTimestamp returns time from timer mechanism - system up time.
  • The best application of this time could be measuring how much time took some operations.

References

  1. Stopwatch.GetTimestamp Method - 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