vb.net 将 unix 时间转换为 DateTime

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25828416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:12:43  来源:igfitidea点击:

Converting unix time to DateTime

vb.netunixdatetime

提问by tmighty

I would like to convert a Unix time stamp to a VB.NET DateTime.

我想将 Unix 时间戳转换为 VB.NET DateTime。

I have tried

我试过了

Public Function UnixToDateTime(ByVal strUnixTime As String) As DateTime

    Dim nTimestamp As Double = strUnixTime
    Dim nDateTime As System.DateTime = New System.DateTime(1970, 1, 1, 0, 0, 0, 0)
    nDateTime.AddSeconds(nTimestamp)

    Return nDateTime

End Function

But when I feed it

但是当我喂它的时候

strUnixTime = "1401093810"

I get the return value

我得到返回值

nDateTime = #1/1/1970#

What am I doing wrong? Thank you

我究竟做错了什么?谢谢

回答by Heinzi

This line of code

这行代码

nDateTime.AddSeconds(nTimestamp)

does notmodify nDateTime. It's like writing a + 3on a line by it's own -- awon't be modified.

没有改变nDateTime。这就像自己写a + 3在一行上一样——a不会被修改。

It does, however, return a new DateTime objectthat contains the incremented value. So, what you actually wanted to write is:

但是,它会返回一个包含递增值的新 DateTime 对象。所以,你真正想写的是:

nDateTime = nDateTime.AddSeconds(nTimestamp)

PS: It appears that your code does not use Option Strict On. It is strongly recommended that you activate Option Strictand use explicit instead of implicit conversions.

PS:您的代码似乎没有使用Option Strict On. 强烈建议您激活Option Strict并使用显式转换而不是隐式转换。