帮助错误地转换日期和时间 [英] help with error converting date and time
问题描述
我有一个文件,该文件具有3个不同的日期时间显示,并且我尝试采用奇数格式并将其转换为另一种格式,当我这样做时,我在
下得到此错误
Message =从字符串"2009年9月21日21:18:55"到类型日期"的转换不是
如果有人可以查看我正在使用的代码,并告诉我我是否做错了,那将很棒.
I have a file that has 3 different date time displays and i m trying to take the odd one and convert it to the other format and when i do i get this error below
Message=Conversion from string "Sept 21, 2009 21:18:55" to type ''Date'' is not
If someone could look at the code i m using and tell me if im doing this wrong that would be great.
If Not Value5 = "" Then
Dim time As DateTime = Value5
Dim format As String = "MMM d, yyyy HH:mm"
Value5 = time.ToString(format)
End If
推荐答案
您正在尝试使用字符串实例化DateTime对象.应该是:
You are trying to instantiate a DateTime object with string. It should be:
If Not Value5 = "" Then
Dim time As DateTime = Convert.ToDateTime(Value5)
Dim format As String = "MMM d, yyyy HH:mm"
Value5 = time.ToString(format)
End If
查看MSDN文档:
http://msdn.microsoft.com/en-us/library/xhz1w05e#Y0 [ ^ ]
Look at MSDN documentation:
http://msdn.microsoft.com/en-us/library/xhz1w05e#Y0[^]
使用此:
var Value5 = string.Format("{0:MMM d, yyyy HH:mm:ss}", time);
这项工作就很好.
在.ToString()方法中,您将区域性设置为非格式!
this work just fine.
in .ToString() method you set the culture not format!
如果我正确理解,问题不是不是将DateTime值转换为String而是将String转换为使用另一种DateTime格式格式化的字符串.
我发现问题出在缩写的月份名称中.
因此,如果您尝试执行以下代码,我想您将解决问题:
If I understand correctly, the problem isn''t to convert a DateTime value to a String one but a String to a String formatted with another DateTime format.
I found that the problem is in the abbreviated month name.
So if you try the follow code I think you''ll solve the problem:
Sub Main()
Dim Value5 As String = "Sept 21, 2009 21:18:55"
Dim ci As New CultureInfo("en-us", False)
Dim dtfi As DateTimeFormatInfo = ci.DateTimeFormat
' This are the default abbreviated month names that cause the problem
'dtfi.AbbreviatedMonthNames = {"Gen", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ""}
' Try the follow updated ...
dtfi.AbbreviatedMonthNames = {"Gen", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec", ""}
If Not Value5 = "" Then
Dim time As DateTime = Convert.ToDateTime(Value5, dtfi)
Dim format As String = "MMM d, yyyy HH:mm"
Value5 = time.ToString(format)
End If
Console.WriteLine(Value5)
Console.ReadLine()
End Sub
希望对您有所帮助
詹洛伦佐(Gianlorenzo)
I hope I was helpful
Gianlorenzo
这篇关于帮助错误地转换日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!