我遇到了一个我无法解决的问题。有人可以帮忙吗?这就是我需要的东西,例如,我在字符串中有一个日期,想要得到日期,我该怎么办?
汽车02/22/11
“汽车”可以改变为任何东西,因为它代表了描述。但就像我说的,我只需要日期部分。提前致谢。
答案 0 :(得分:3)
在您的情况下,您可以使用最后8个字符并将其传递给DateTime.Parse。
DateTime.Parse(str.Substring(str.Length - 8));
在更复杂的情况下,您可以使用Regex类。 (但在这种情况下,这是一种矫枉过正的行为。)
答案 1 :(得分:2)
使用正则表达式查找日期输入:
Regex.Match(@"^([1-9]|0[1-9]|1[012])[- /.]([1-9]|0[1-9]|[12][0-9]|3[01])[- /.][0-9]{4}$")
正则表达式取自:http://dotnetrush.blogspot.com/2006/12/c-date-format-regular-expression.html
答案 2 :(得分: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
}
答案 3 :(得分:0)
Dim datePart as String = input.Split(" ")(1)
Dim dt as DateTime = DateTime.Parse(datePart)
答案 4 :(得分:0)
如果描述始终是单个单词,则可以从第一个空格到字符串末尾获取子字符串。
答案 5 :(得分:0)
string myString = "Cars 02/22/11";
string stringDate = myString.Substring(myString.Length-8);
DateTime dateTime = Convert.ToDateTime(stringDate);
答案 6 :(得分: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
答案 7 :(得分: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