开发者

how to convert string to datetime in .net

hey guys, i have a datetime in string format and n开发者_JAVA技巧ow i want to convert the same in datetime format, in the string i have following string.... (12.01.2011) dd.mm.yyyy format, now i want this format to be converted in datetime format because i want to store this in database which has a field whose datatype is datetime....

Please reply as soon as possible. Thanks and regards Abbas electricwala.


Use DateTime.Parse and be aware of the regional settings. You can bypass regional settings by providing your own CultureInfo. I don't know which language you use, but my language (danish) support your date format (dd.mm.yyyy). Thus, I use the following syntax:

        string inputDate = "31.12.2001";
        CultureInfo cultureInfo =  new CultureInfo("da-DK");

        DateTime parsedDate = DateTime.Parse(inputDate, cultureInfo);

Alternatively, you can split the input string, and construct a new Date.

Regards, Morten


See the DateTime.Parse function in msdn: http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx


As you have an exact dateformat you don't need to worry about regional settings:

DateTime.ParseExact(inputDate , "dd.MM.yyyy", null)

Or with error-checking:

DateTime value;
if (DateTime.TryParseExact(inputDate , "dd.MM.yyyy", null, 
    DateTimeStyles.None, out value))
{
   // use value
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜