2011-06-21 26 views
2

我遇到了一个我无法解决的问题。有人可以帮忙吗?这就是我需要的,例如,我有一个字符串中的日期,想要取得日期,我该怎么做?如何从字符串中获取日期

汽车11年2月22日

“汽车总动员”可以改变任何东西,因为它代表的说明。但就像我说的,我只需要日期部分。先谢谢了。

回答

0
Dim datePart as String = input.Split(" ")(1) 
Dim dt as DateTime = DateTime.Parse(datePart) 
+4

不好的事情会发生。 – Graham

3

在你的情况下,你可以取最后8个字符并将其传递给DateTime.Parse。

DateTime.Parse(str.Substring(str.Length - 8)); 

在更复杂的情况下,您可以使用正则表达式类。 (但是在这种情况下它是一个矫枉过正的问题。)

+0

感谢,制定了出色的。 – jack

0

如果描述始终是一个单词,则可以从第一个空白到字符串的末尾获取子字符串。

0
string myString = "Cars 02/22/11"; 
string stringDate = myString.Substring(myString.Length-8); 

DateTime dateTime = Convert.ToDateTime(stringDate); 
0
Sub Main() 
    ' We want to split this input string 
    Dim rawstring As String = "Car 29/3/2011" 

    ' Split string based on spaces 
    Dim stringarray As String() = rawstring.Split(New Char() {" "c}) 

    ' Use For Each loop over words and display them 
    Dim datestring As String = stringarray(0); 
End Sub 
0

这会找到一个字符串的任何日期,只要它们是用空格分开:

 Dim startString As String = "Cars 02/22/11" 
    Dim tempParts As String() 
    Dim testValue As String 
    Dim tempDate As DateTime 

    tempParts = startString.Split(" ") 

    For Each testValue In tempParts 
     If DateTime.TryParse(testValue, tempDate) = True Then 
      MessageBox.Show(String.Format("Date in string: {0}", tempDate)) 
     End If 
    Next 
2

使用正则表达式并查找日期输入。如果日期位于字符串中间而不仅仅是结尾,这也将起作用。

Dim dateMatch As Match = Regex.Match(inputString, "([1-9]|0[1-9]|1[012])[- /.]([1-9]|0[1-9]|[12][0-9]|3[01])[- /.][0-9]{4}") 
Dim parsedDate As DateTime 
If dateMatch.Value.Length > 0 AndAlso DateTime.TryParse(dateMatch.Value, parsedDate) Then 
    'you have a date time! 
Else 
    'you didn't get anything useful back from the regex, OR what you got back was not a legitimate date-time 
End If 

在C#中:如果描述中包含空格,

Match dateMatch = Regex.Match(inputString, @"([1-9]|0[1-9]|1[012])[- /.]([1-9]|0[1-9]|[12][0-9]|3[01])[- /.][0-9]{4}"); 
DateTime parsedDate; 
if (dateMatch.Value.Length > 0 && DateTime.TryParse(dateMatch.Value, out parsedDate)) { 
    //you have a date time! 
} 
else { 
    //you didn't get anything useful back from the regex, OR what you got back was not a legitimate date-time 
}