我的string
看起来像“2012年12月17日”,我想将其转换为datetime
,格式为 dd / MM月/年。
我一直在this链接,但这与我想要实现的目标相反。
我可以通过删除后缀(“17th”中的“th”)来做到这一点,然后将其转换为datetime
,但是有直接方式实现这个目标?
C#代码也可以。
这是我现在的代码,但它看起来很难看......哈哈。
Private Function gettime(ByVal thetime As String) As DateTime
Dim result As DateTime
Dim str1 As String = thetime
Dim str2 As String = str1
Dim ind As Integer = 0
ind = str1.IndexOf(" ")
str2 = str1.Substring(0, ind)
str2 = Trim(StrReverse(str2))
str2 = str2.Substring(2, 2)
str2 = StrReverse(str2)
ind = str1.IndexOf(" ")
str1 = str2 & str1.Substring(ind)
result = DateTime.Parse(str1)
Return result
End Function
答案 0 :(得分:3)
您可以为解析添加多种格式。
Dim formats() As String = {"dd MMMM yyyy", "dd\s\t MMMM yyyy", "dd\t\h MMMM yyyy"}
d = DateTime.ParseExact(s, formats, Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None)
答案 1 :(得分:1)
你有没试过?
试试这个:
Dim time As DateTime = DateTime.Parse("17th December 2012")
<强>更新强>
如果问题只是序数,您可以创建一个简单的过程来删除它们:
Sub RemoveOrdinals(time As String) As String
time = time.Replace("nd", "")
time = time.Replace("rd", "")
time = time.Replace("st", "")
time = time.Replace("th", "")
Return time
End Sub
并在进行DateTime
转换之前简单地调用它。
答案 2 :(得分:1)
此代码适用于我:
C#:
string datestring = "17th December 2012";
int indexOfFirstLetter = Regex.Match(
datestring,
"[a-z]",
RegexOptions.IgnoreCase).Index;
datestring = datestring.Remove(indexOfFirstLetter, 2);
DateTime date = DateTime.Parse(datestring);
VB.Net:
Dim datestring As String = "17th December 2012"
Dim indexOfFirstLetter As Integer = Regex.Match( _
datestring, _
"[a-z]", _
RegexOptions.IgnoreCase).Index
datestring = datestring.Remove(indexOfFirstLetter, 2)
Dim yourdate As DateTime = DateTime.Parse(datestring)