Languages
[Edit]
EN

C# / .NET - get current time in milliseconds

5 points
Created by:
Marcin
2544

In C# / .NET it is possible to get time in milliseconds in few ways.

1. Custom milliseconds timestamp example

long time = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

Console.WriteLine(time);

Output:

63701247264339
Note: be careful using this example, because time here is not measured from 1970-01-01.

2. Custom Unix milliseconds timestamp example

public static class TimeUtils
{
	public static long GetUnixTimstamp(DateTime date)
	{
		DateTime point = new DateTime(1970, 1, 1);
		TimeSpan time = date.Subtract(point);

		return (long)time.TotalMilliseconds;
	}

	public static long GetUnixTimstamp()
	{
		return GetUnixTimstamp(DateTime.UtcNow);
	}
}

Example:

Console.WriteLine(TimeUtils.GetUnixTimstamp());

Output:

1565647530865

3. .NET 4.6 API Unix milliseconds timestamp example

DateTimeOffset now = (DateTimeOffset)DateTime.UtcNow;

Console.WriteLine(now.ToUnixTimeMilliseconds());

Output:

1565647040281

References:

  1. DateTime Class - Microsoft Docs
  2. DateTimeOffset.ToUnixTimeMilliseconds 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