在C#.net中将字符串转换为datetime

有人可以帮我转换字符串14/04/2010 10:14:49.PM到C#.net的日期时间而不会丢失时间格式吗?

var date = DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss.tt", null); 

用于字符串表示

 date.ToString(@"dd/MM/yyyy hh:mm:ss.tt"); 

您还可以创建这样的扩展方法:

  public enum MyDateFormats { FirstFormat, SecondFormat } public static string GetFormattedDate(this DateTime date, MyDateFormats format) { string result = String.Empty; switch(format) { case MyDateFormats.FirstFormat: result = date.ToString("dd/MM/yyyy hh:mm:ss.tt"); break; case MyDateFormats.SecondFormat: result = date.ToString("dd/MM/yyyy"); break; } return result; } 
 DateTime result =DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy HH:mm:ss.tt",null); 

您现在可以看到格式提供程序的PM或AM和null值

 DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss"); 
 DateTime.Parse(@"14/04/2010 10:14:49.PM"); 

应该工作,而不是在VS附近,所以我不能尝试

使用转换function

 using System; using System.IO; namespace stackOverflow { class MainClass { public static void Main (string[] args) { Console.WriteLine(Convert.ToDateTime("14/04/2010 10:14:49.PM")); Console.Read(); } } } 

我建议使用DateTime.ParseExact因为根据当前线程区域设置, Parse方法的行为略有不同。

 DateTime.ParseExact(yourString, "dd/MM/yyyy hh:mm:ss.tt", null)