Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you think you have some skills to help others

help someone and become a part of our community - List Q & A

C# / .NET - get current time in milliseconds

0 contributions
5 points

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

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more