开发者

how to get date out of string

I'm having a little problem which I cant resol开发者_运维问答ve. Can someone help? Here's what I need, for example, I have a date in a string and want to get the date, how can I do so?

Cars 02/22/11

"Cars" can change to anything because it represent a description. But like I said, I just need the date part.


In your case you can just take last 8 charactes and pass it DateTime.Parse.

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

In more complex cases you can use Regex class. (But it's an overkill in this case.)


Use a regular expression and look for the date input:

Regex.Match(@"^([1-9]|0[1-9]|1[012])[- /.]([1-9]|0[1-9]|[12][0-9]|3[01])[- /.][0-9]{4}$")

Regex taken from: http://dotnetrush.blogspot.com/2006/12/c-date-format-regular-expression.html


Use a regular expression and look for the date input. This will also work if the date is somewhere mid-string rather than just on the end.

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

In 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
}


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


If the description is always going to be a single word, you could get the substring from the first whitespace to the end of the string.


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

DateTime dateTime = Convert.ToDateTime(stringDate);


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


This will find any dates in a string as long as they are separated by spaces:

        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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜