DateTime to UnixTime Stamp in .net

浪子不回头ぞ 提交于 2019-11-27 06:20:45

问题


Is there any function in vb dot net to convert datetime to unix time stamp If I google I get only the vice versa but not vb.net to unix time stamp

Any help is appreciated


回答1:


{Edit} removed old reference link

Seconds since Jan 1, 1970 = unix time

To get this in VB.NET see below example (in example using DateTime.UtcNow, but you can plug in any DateTime you want there)

Dim uTime As Integer
uTime = (DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds



回答2:


I wrote these at some point - all similar to the above just with a little more detail on the old summer time adjustment thing for me here in the UK.

Public Function UnixToTime(ByVal strUnixTime As String) As Date
    UnixToTime = DateAdd(DateInterval.Second, Val(strUnixTime), #1/1/1970#)
    If UnixToTime.IsDaylightSavingTime = True Then
        UnixToTime = DateAdd(DateInterval.Hour, 1, UnixToTime)
    End If
End Function

Public Function TimeToUnix(ByVal dteDate As Date) As String
    If dteDate.IsDaylightSavingTime = True Then
        dteDate = DateAdd(DateInterval.Hour, -1, dteDate)
    End If
    TimeToUnix = DateDiff(DateInterval.Second, #1/1/1970#, dteDate)
End Function



回答3:


Looking at http://www.codeproject.com/KB/cs/timestamp.aspx it shows unix->.net so you can go backwards most likely:

DateTime dt = "the date";
DateTime start= new System.DateTime(1970, 1, 1, 0, 0, 0, 0);

TimeSpan ts = (dt - start);

ts.TotalSeconds //unix timestamp

or something similar will do it.

note, this has not been tested by me so it probably wont work :)




回答4:


In javascript, at least, unix timestamps are milliseconds, and I found a case where I needed them. This code makes use of .Net using 10,000 ticks / millisecond. Here's the code I used:

Public Module UnixTime
    Const UnixEraStartTicks As Long = 621355968000000000
    <Extension> Public Function UnixTimestamp(value As Date) As Long
        Dim UnixEraTicks = value.Ticks - UnixEraStartTicks
        Return UnixEraTicks \ 10000
    End Function
    Public Function DateFromUnix(timestamp As Long) As Date
        Return New Date(UnixEraStartTicks + timestamp * 10000)
    End Function
End Module


来源:https://stackoverflow.com/questions/1942519/datetime-to-unixtime-stamp-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!