tags:

views:

58

answers:

2
string strdate="15/06/2010";

DateTime dt = 
     DateTime.Parse(strdate, 
     System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat);

i cannot able to get the datetime value as dd/mm/yyyy. it is giving exception 'string is not recognized as a valid datetime'

oly if it is in 06/15/2010 it is working. how to get the same format in dt.

+4  A: 

Well, presumably your thread's current culture expects MM/dd/yyyy. If you want to use dd/MM/yyyy then you should specify that explicitly. Personally I prefer ParseExact instead of Parse, as that gives more control. I would use something like:

DateTime dt = DateTime.ParseExact(strdate, "dd/MM/yyyy",
    CultureInfo.InvariantCulture);

Note that if this is user input, you may want to use TryParseExact instead.

Jon Skeet
A: 

You're currently using the current culture, which seems to be set up for US style date formats. Try this instead:

DateTime.Parse(strdate, System.Globalization.CultureInfo.CreateSpecificCulture("en-GB"));

This tells the function to use UK date style format which works. You might want to change the en-GB to whatever culture your dates will be in. If you have many calls where the culture is important it might also be worth to set it for the whole thread rather than call by call.

ho1