开发者

ASP.NET: Get milliseconds since 1/1/1970

开发者 https://www.devze.com 2023-02-24 23:12 出处:网络
I have an ASP.NET, VB.NET Date, and I\'m trying to get the number of milliseconds since January 1st, 1970. I tried looking for a method in MSDN, but I couldn\'t find开发者_JS百科 anything. Does anyone

I have an ASP.NET, VB.NET Date, and I'm trying to get the number of milliseconds since January 1st, 1970. I tried looking for a method in MSDN, but I couldn't find开发者_JS百科 anything. Does anyone know how to do this?


Starting with .NET 4.6, The method ToUnixTimeMilliseconds provides a more accurate solution.

From DateTimeOffset:

DateTimeOffset.Now.ToUnixTimeMilliseconds()

From DateTime:

new DateTimeOffset(dateTime).ToUnixTimeMilliseconds()

Source: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tounixtimemilliseconds?view=netframework-4.6#System_DateTimeOffset_ToUnixTimeMilliseconds


You can subtract any two DateTime instances and get TimeSpan and TotalMilliseconds would give you total milliseconds. Sample below.

    DateTime dt1970 = new DateTime(1970, 1, 1);
    DateTime current = DateTime.Now;//DateTime.UtcNow for unix timestamp
    TimeSpan span = current - dt1970;
    Console.WriteLine(span.TotalMilliseconds.ToString());

one liner

//DateTime.MinValue is 01/01/01 00:00 so add 1969 years. to get 1/1/1970
DateTime.Now.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds;


Alternatively, you can use the Ticks property and avoid construction of a temporary object:

long epochTime = (DateTime.UtcNow.Ticks - 621355968000000000) / 10000;

However, this isn't entirely

Reasoning:

DateTime d = new DateTime(1970, 01, 01);
var temp = d.Ticks; // == 621355968000000000


This will provide the UNIX Epoch in milliseconds. (Respects UTC time instead of your local time)

Split(DateTime.UtcNow.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds(), ".", 2)(0)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号