vb.net 将字符串转换为日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6387874/
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
Convert String to Date Time
提问by MNVR
Possible Duplicate:
Convert string to DateTime in c#
可能的重复:
在 C# 中将字符串转换为 DateTime
I am trying to convert a string in the format "20110617111051" to date time. Currently I am using String.SubString() function to extract year, month, day, time to format a standard string and then using Convert.ToDateTime(string). Is there any other simple way to do this?
我正在尝试将格式为“20110617111051”的字符串转换为日期时间。目前我正在使用 String.SubString() 函数来提取年、月、日、时间来格式化标准字符串,然后使用 Convert.ToDateTime(string)。有没有其他简单的方法可以做到这一点?
Dim x as String="20110617110715"
Dim standard as string = x.SubString(0,4) & "-" & x.SubString(4,2) & "-" & x.SubString(6,2) 'and time
Dim dateTime as DateTime = Convert.ToDateTime(standard)
回答by Anthony Pegram
You can use DateTime.ParseExact
.
您可以使用DateTime.ParseExact
.
DateTime date = DateTime.ParseExact(x, "yyyyMMddHHmmss", CultureInfo.CurrentCulture);
VB
VB
Dim myDate as DateTime = DateTime.ParseExact(x, "yyyyMMddHHmmss", CultureInfo.CurrentCulture)
回答by Donut
Use the DateTime.ParseExact
function in conjunction with the exact format of your input string. Example:
将该DateTime.ParseExact
函数与输入字符串的确切格式结合使用。例子:
C#:
C#:
string input = "20110617111051";
string format = "yyyyMMddhhmmss";
DateTime dateTime = DateTime.ParseExact(input, format, CultureInfo.InvariantCulture);
VB:
VB:
Dim input As String = "20110617111051"
Dim format As String = "yyyyMMddhhmmss"
Dim dateTime as DateTime = DateTime.ParseExact(input, format, CultureInfo.CurrentCulture)
See this pagefor more info on custom date and time strings.
有关自定义日期和时间字符串的更多信息,请参阅此页面。