开发者

converting string to valid datetime

string strdate="15/06/2010";

DateTime dt = 
     DateTime.Parse(str开发者_运维百科date, 
     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.


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜