C# 如何在C中将1/1/1300日期转换为日期时间值#

C# 如何在C中将1/1/1300日期转换为日期时间值#,c#,.net,datetime,C#,.net,Datetime,我有一个场景,其中我有一个日期值,如1/1/1300,我想将其转换为datetime对象,以便进行比较。在Sql Server中,我使用datetime2来表示这个日期,它工作得很好,但我不知道如何在C#中将其转换为datetime2?Im使用.Net 4您可以使用以下方法: 或者,如果日期格式错误或表示无效日期,则使用: DateTime date; if (DateTime.TryParseExact("1/1/1300", "d/M/yyyy", CultureInfo.Invariant

我有一个场景,其中我有一个日期值,如1/1/1300,我想将其转换为datetime对象,以便进行比较。在Sql Server中,我使用datetime2来表示这个日期,它工作得很好,但我不知道如何在C#中将其转换为datetime2?Im使用.Net 4

您可以使用以下方法:

或者,如果日期格式错误或表示无效日期,则使用:

DateTime date;
if (DateTime.TryParseExact("1/1/1300", "d/M/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
    // parsing was successful => you could use the date here
}
C#中没有DateTime2,只有DateTime:

string dateString = "1/1/1300";
DateTime date = DateTime.Parse(dateString, CultureInfo.InvariantCulture);

如果您要查找的是将
datetime2
SQL数据类型转换为.NET数据类型,请检查以下答案:

这似乎表明类型是相同的
DateTime
,但答案中的代码片段:

new DataColumn("myDate", typeof(DateTime))
我假设如果您使用的是DataReader,您也可以将该值视为
DateTime
,或者如果
DateTime
,则可以将其视为
DateTimeOFfset


如果您使用的是ORM,它将取决于所使用的ORM。如果仍然不起作用,您可能需要指定访问数据库的方式。

我在linq查询中尝试Datetime.ParseExact,它会给出此错误。方法“System.DateTime ParseExact(System.String、System.String、System.IFormatProvider)”不支持到SQL的转换
new DataColumn("myDate", typeof(DateTime))