简体   繁体   English

如何在.net中将字符串转换为日期时间

[英]how to convert string to datetime in .net

hey guys, i have a datetime in string format and now 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.... 嘿家伙,我有一个字符串格式的日期时间,现在我想转换相同的日期时间格式,在字符串我有以下字符串....(12.01.2011)dd.mm.yyyy格式,现在我想要这种格式要以datetime格式转换,因为我想将它存储在数据库中,该数据库的数据类型为datetime ....

Please reply as soon as possible. 请尽可能尽快回复。 Thanks and regards Abbas electricwala. 感谢和问候Abbas electricwala。

请参阅msdn中的DateTime.Parse函数: http//msdn.microsoft.com/en-us/library/w2sa9yss.aspx

Use DateTime.Parse and be aware of the regional settings. 使用DateTime.Parse并了解区域设置。 You can bypass regional settings by providing your own CultureInfo. 您可以通过提供自己的CultureInfo来绕过区域设置。 I don't know which language you use, but my language (danish) support your date format (dd.mm.yyyy). 我不知道你使用哪种语言,但我的语言(丹麦语)支持你的日期格式(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. 或者,您可以拆分输入字符串,并构造一个新的Date。

Regards, Morten 此致,莫滕

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM