我如何在c#中将字符串转换为日期时间#

cmr*_*ema 0 c#

可能重复:
将字符串转换为datetime使用C#
将字符串转换为DateTime C#.net

嗨,我有一个字符串,其中包含日期时间,格式为dd/mm/yyyy hh:mm:ss.ms

即日期/月/年小时:分钟:秒.毫秒.例如.18/03/2011 15:16:57.487

如何使用c#将此字符串转换为datetime

关心cmrhema.

Vol*_*lem 8

您可以使用DateTime.Parse或DateTime.ParseExact

  DateTime dateValue;
  string dateString = "2/16/2008 12:15:12 PM";
  try {
     dateValue = DateTime.Parse(dateString);
     Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
  }   
  catch (FormatException) {
     Console.WriteLine("Unable to convert '{0}'.", dateString);
  }
Run Code Online (Sandbox Code Playgroud)

对于ParseExact

dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
try 
{
     result = DateTime.ParseExact(dateString, format, provider);
     Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) 
{
     Console.WriteLine("{0} is not in the correct format.", dateString);
}
Run Code Online (Sandbox Code Playgroud)