我有一个字符串格式的日期和时间:

"2011-03-21 13:26" //year-month-day hour:minute

如何将其解析为System.DateTime?

如果可能的话,我想使用DateTime.Parse()或DateTime.ParseExact()这样的函数,以便能够手动指定日期的格式。


当前回答

DateTime.Parse()应该适用于该字符串格式。参考:

http://msdn.microsoft.com/en-us/library/1k1skd40.aspx#Y1240

它是否为你抛出FormatException ?

其他回答

DateTime.Parse()将尝试找出给定日期的格式,它通常做得很好。如果你能保证日期总是在一个给定的格式,那么你可以使用ParseExact():

string s = "2011-03-21 13:26";

DateTime dt = 
    DateTime.ParseExact(s, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

(但请注意,在日期不是预期格式的情况下,使用TryParse方法之一通常更安全)

在构造格式字符串时,请务必检查自定义日期和时间格式字符串,特别是注意字母和大小写的数量(即。“MM”和“MM”的意思非常不同)。

c#格式字符串的另一个有用资源是c#中的字符串格式化

简单而直接的答案——>

using System;

namespace DemoApp.App

{
public class TestClassDate
{
    public static DateTime GetDate(string string_date)
    {
        DateTime dateValue;
        if (DateTime.TryParse(string_date, out dateValue))
            Console.WriteLine("Converted '{0}' to {1}.", string_date, dateValue);
        else
            Console.WriteLine("Unable to convert '{0}' to a date.", string_date);
        return dateValue;
    }
    public static void Main()
    {
        string inString = "05/01/2009 06:32:00";
        GetDate(inString);
    }
}
}

/**
 * Output:
 * Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
 * */
var dateStr = @"2011-03-21 13:26";
var dateTime = DateTime.ParseExact(dateStr, "yyyy-MM-dd HH:mm", CultureInfo.CurrentCulture);

查看其他格式字符串的链接!

DateTime.Parse()应该适用于该字符串格式。参考:

http://msdn.microsoft.com/en-us/library/1k1skd40.aspx#Y1240

它是否为你抛出FormatException ?

将一个人类可读的字符串的值放入.NET DateTime中,代码如下:

DateTime.ParseExact("April 16, 2011 4:27 pm", "MMMM d, yyyy h:mm tt", null);