Top community members
All Wiki Articles Create Wiki Article

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here

co-founder

C# / .NET - create date and time from milliseconds

0 contributions
12 points

In C# / .NET it is possible to get DateTime instance from total milliseconds in few ways.

1. DateTime from total milliseconds example

public static class TimeUtils
{
	public static DateTime GetDateTime(long milliseconds, 
			DateTimeKind kind = DateTimeKind.Utc)
	{
		long ticks = milliseconds * TimeSpan.TicksPerMillisecond;

		return new DateTime(ticks, kind );
	}
}

Example:

Console.WriteLine(TimeUtils.GetDateTime(0));
Console.WriteLine(TimeUtils.GetDateTime(63701329632387));

Output:

01/01/0001 00:00:00
08/13/2019 21:47:12
Note: time is measured since 01-01-0001 00:00:00.000.

2. DateTime from Unix total milliseconds custom example

public static class TimeUtils
{
	public static DateTime GetDateTime(long milliseconds)
	{
		long ticks = DateTime.UnixEpoch.Ticks + milliseconds 
			* TimeSpan.TicksPerMillisecond;

		return new DateTime(ticks, DateTimeKind.Utc);
	}
}

Example:

Console.WriteLine(TimeUtils.GetDateTime(0));
Console.WriteLine(TimeUtils.GetDateTime(1565732877968));

Output:

01/01/1970 00:00:00
08/13/2019 21:47:57
Note: Unix time is measured from 01-01-1970 UTC date.

3. DateTimeOffset.FromUnixTimeMilliseconds method example

Console.WriteLine(DateTimeOffset.FromUnixTimeMilliseconds(0));
Console.WriteLine(DateTimeOffset.FromUnixTimeMilliseconds(1565732877968));

Output:

01/01/1970 00:00:00
08/13/2019 21:47:57
Node: this approach is available since .NET 4.6.

References

  1. DateTime Struct - 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