Languages
[Edit]
EN

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

12 points
Created by:
AnnLen
9180

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