I have a string of the form "ORDER20100322194007", it "20100322194007" Date and time 2010-03-22 19:40:07.000. How to parse a string and get the contained object DateTime?
+3
A:
You can use DateTime.ParseExact method to specify the format that should be used while parsing.
Giorgi
2010-04-01 13:12:15
+15
A:
Will it always start with ORDER
?
string pattern = "'ORDER'yyyyMMddHHmmss";
DateTime dt;
if (DateTime.TryParseExact(text, pattern, CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
// dt is the parsed value
}
else
{
// Invalid string
}
If the string being invalid should throw an exception, then use DateTime.ParseExact
instead of DateTime.TryParseExact
If it doesn't always begin with "ORDER" then do whatever you need to in order to get just the date and time part, and remove "'ORDER'" from the format pattern above.
Jon Skeet
2010-04-01 13:13:05
Correct DateTimesStyles.None on DateTimeStyles.None
Anry
2010-04-01 13:31:15
@Anry: Thanks, fixed.
Jon Skeet
2010-04-01 13:31:39
A:
If you don't have a fixed structure of your string say order will not always be there then you can use regex to separate the numbers and characters and then use convert to datetime function for the numbers separated.
Samiksha
2010-04-01 13:15:17