tags:

views:

150

answers:

3

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
+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
Correct DateTimesStyles.None on DateTimeStyles.None
Anry
@Anry: Thanks, fixed.
Jon Skeet
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