string 在 vb.net 中将字符串转换为日期时间

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

Convert string to datetime in vb.net

vb.netstringdatetime

提问by ErocM

I have a datetime that looks like this:

我有一个看起来像这样的日期时间:

201210120956
ccyyMMDDhhmm

When I try this:

当我尝试这个时:

Dim convertedDate As Date = Date.Parse(DateString)
Return convertedDate

I get back this:

我得到这个:

#10/12/2012#

I'm losing the time on it.

我正在浪费时间。

I've read this convert string to datetime vb.netbut when I use datetime.ParseExact()I get:

我已经阅读了这个将字符串转换为日期时间的 vb.net但是当我使用时datetime.ParseExact()我得到:

cannot resolve symbol 'ParseExact'

无法解析符号“ParseExact”

Is there a way to convert this to a date time without using substring? A straight conversion?

有没有办法在不使用子字符串的情况下将其转换为日期时间?直接转换?

回答by Steve

Pass the decode pattern to ParseExact

将解码模式传递给 ParseExact

Dim d as string = "201210120956"
Dim dt = DateTime.ParseExact(d, "yyyyMMddhhmm", Nothing)

ParseExact is available onlyfrom Net FrameWork 2.0.
If you are still on 1.1 you could use Parse, but you need to provide the IFormatProvider adequate to your string

ParseExact在 Net FrameWork 2.0 中可用。
如果您仍然使用 1.1,您可以使用 Parse,但您需要提供适合您的字符串的 IFormatProvider

回答by Aghilas Yakoub

You can try with ParseExactmethod

你可以试试ParseExact方法

Sample

样本

Dim format As String  
format = "d" 
Dim provider As CultureInfo = CultureInfo.InvariantCulture
result = Date.ParseExact(DateString, format, provider)

回答by Josh Newton

As an alternative, if you put a space between the date and time, DateTime.Parsewill recognize the format for you. That's about as simple as you can get it. (If ParseExactwas still not being recognized)

作为替代方案,如果您在日期和时间之间放置一个空格,DateTime.Parse则会为您识别格式。这很简单,你可以得到它。(如果ParseExact还没有被识别)