vb.net 如何将整数转换为日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18207611/
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 14:37:59  来源:igfitidea点击:

How do I convert and integer to datetime

asp.netvb.net

提问by Jonathan Lockley

I am using ASP.NET Visual Basic.

我正在使用 ASP.NET Visual Basic。

I have an integer field in my database which I need to read as a date e.g. 20130813. But at the moment it says I cannot convert to datetime.

我的数据库中有一个整数字段,我需要将其读取为日期,例如 20130813。但目前它说我无法转换为日期时间。

Is there a way to split the integer up into DD, MM, YYYY so I could even store those in variables to then use to create a date. Or a simple way of just converting to date.

有没有办法将整数拆分为 DD、MM、YYYY,这样我什至可以将它们存储在变量中,然后用于创建日期。或者只是转换为日期的简单方法。

Thanks for your time.

谢谢你的时间。

回答by SysDragon

Try this:

尝试这个:

Dim provider As CultureInfo = CultureInfo.CurrentCulture
Dim sData As String = "20130813" 
Dim myDate As Date = Date.ParseExact(sData, "yyyyMMdd", provider)

You can convert your number to string easily, if needed:

如果需要,您可以轻松地将您的数字转换为字符串:

Dim myNum As Integer = 20130813
sData = myNum.ToString()

See MSDN Documentationfor more information.

有关更多信息,请参阅MSDN 文档

回答by Andrew Morton

As you're starting with a number, you could either convert it to a string and use DateTime.TryParseExact, or use a bit of integer arithmetic to split it up:

当您从数字开始时,您可以将其转换为字符串并使用 DateTime.TryParseExact,或者使用一些整数算法将其拆分:

Dim n As Integer = 20130813
Dim yr As Integer = n \ 10000
Dim mon As Integer = (n - 10000 * yr) \ 100
Dim d As Integer = n Mod 100
Dim dt As New DateTime(yr, mon, d)

回答by Santiago Mu?oz

Quicker:

更快:

Dim d As Date = Date.FromOADate(41498)

(from Robert Shuttin experts-exchange.com)

(从罗伯特Shuttexperts-exchange.com

回答by sk2185

Private Sub stringtodate(ByVal dateval As String)
    Dim yy As String
    Dim mm As String
    Dim dd As String
    Dim newdate As Date
    yy = dateval.Substring(0, 4)
    mm = dateval.Substring(4, 2)
    dd = dateval.Substring(6, 2)
    newdate =Convert.ToDateTime(dd & "/" & mm & "/" & yy)
    MsgBox(newdate.ToString())
End Sub