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

dot*_*cks 5 c# datetime

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

And*_*ich 5

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

用于字符串表示

date.ToString(@"dd/MM/yyyy hh:mm:ss.tt");
Run Code Online (Sandbox Code Playgroud)

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

    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;
    }
Run Code Online (Sandbox Code Playgroud)


cae*_*say 0

DateTime.Parse(@"14/04/2010 10:14:49.PM");
Run Code Online (Sandbox Code Playgroud)

这应该可行,目前不在 VS 附近,所以我无法尝试