tags:

views:

62

answers:

4

hi

i get date & time from Text file - to my string var in my C# program.

i need to convert this string var to datetime var.

how to do it, if i get unexpected type of date & time ?

and if i dont know the type of region on the host computer (when i Spread my program) ?

thank's in advance

+1  A: 

Use TryParse which will return a boolean saying if the date is valid or not.

    string dateString = "03/01/2009 10:00 AM";
    CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
    DateTimeStyles styles DateTimeStyles.None;
    DateTime dateResult;

    if(DateTime.TryParse(dateString, culture, styles, out dateResult))
    {
        do something with dateResult
    }

TryParse docs

skyfoot
A: 

TryParse is what you want.

DateTime result;

if(!DateTime.TryParse(unpredictableDate, out result))
{
    throw new ArgumentException("Argument '" + unpredictableDate + "' was not a recognizable date format.");
}
Brad
Rejecting it with an exception is good. But how do you figure that "bad format" is *more* informative then the exception you'd get when you just use DateTime.Parse?
Hans Passant
@Hans, because the OP can copy/paste my code and instead of just running it, incorporate it into a larger framework where he customizes the error message to his liking. I modified the error message to be a little more helpful. If you are bulk processing, I would recommend inserting the errant record into a table for manual processing later, then continuing your batch.
Brad
A: 

DateTime.Parse() uses the culture settings from the PC where the app is running. That means the user can input the date formats of his culture.

If you do not want it this way specify the Invariant Culture when parsing then always english culture settings are assumed.

codymanix
A: 

If you are enforcing a specific date/time format, try using DateTime.ParseExact.

Antony Scott