C#DateTime转换或解析特定格式?

时间:2012-03-13 01:46:32

标签: c#

我正在尝试将以下字符串转换为c#中的DateTime值:

  

2012年3月1日

但是在调用Convert.ToDateTime或DateTime.Parse时,我一直收到此错误。

  

字符串未被识别为有效的DateTime。

我认为需要使用自定义日期格式,但我不知道格式是什么。

如何将上述格式的字符串转换为DateTime值?

3 个答案:

答案 0 :(得分:6)

DateTime.ParseExact(yourString, "d MMMM yyyy", new CultureInfo("en-US"))

答案 1 :(得分:1)

您可以通过从当前线程获取cultureinfo来查找支持的日期时间模式。

static void Main(string[] args)
        {
            const string date = "1 03 2012";

            Console.WriteLine(Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongTimePattern);
            Console.WriteLine(Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortTimePattern);
            Console.WriteLine(Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern);
            Console.WriteLine(Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern);

            Console.WriteLine(DateTime.Parse(date));
            Console.WriteLine(Convert.ToDateTime(date));


            Console.ReadLine();
        }

答案 2 :(得分:0)

这对我有用

     string s = "1 March 2012";
     DateTime dateTime = DateTime.Parse(s);
相关问题