在C#.net中将字符串转换为日期时间

在C#.net中将字符串转换为日期时间,c#,datetime,C#,Datetime,有人能帮我将字符串14/04/2010 10:14:49.PM转换为C#net中的datetime而不丢失时间格式吗 DateTime.Parse(@"14/04/2010 10:14:49.PM"); 这应该行得通,目前还不能接近VS,所以我不能尝试 DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss"); 用于字符串表示 date.ToString(@"dd/MM/yyyy hh:mm:ss.tt");

有人能帮我将字符串14/04/2010 10:14:49.PM转换为C#net中的datetime而不丢失时间格式吗

DateTime.Parse(@"14/04/2010 10:14:49.PM");
这应该行得通,目前还不能接近VS,所以我不能尝试

DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss");
用于字符串表示

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;
    }
使用转换函数

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)

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

您所说的时间格式是什么意思?它的日期/月份格式不明确,因此在某些情况下不起作用。我同意Myster的看法。该行为依赖于区域设置。假设这是DateTimeFormatInfo.CurrentInfo的正确格式,则应能正常工作。字符串表示形式应使用hh而不是hh。在解析过程中,差异并没有那么大,但是对于输出,您将得到23h而不是11h(PM),扩展方法也需要是静态的。哦,是的。这只是因为我没有在我身边。更新。
DateTime.ParseExact(yourString,
    "dd/MM/yyyy hh:mm:ss.tt", null)
DateTime result =DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy HH:mm:ss.tt",null);