简体   繁体   English

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

[英]How to convert 1/1/1300 date to datetime value in C#

I have a scenario where i have date value like 1/1/1300 and i want to convert it to datetime object for comparison purposes. 我有一种情况,我有一个日期值,例如1/1/1300,并且我想将其转换为datetime对象以进行比较。 In Sql Server i use datetime2 for this date and it works perfect but i dont know how to convert it to datetime2 in C#? 在Sql Server中,我使用datetime2作为该日期,它可以完美工作,但是我不知道如何在C#中将其转换为datetime2? Im using .Net 4 我正在使用.Net 4

You could use the ParseExact method: 您可以使用ParseExact方法:

DateTime date = DateTime.ParseExact("1/1/1300", "d/M/yyyy", CultureInfo.InvariantCulture);

or use TryParseExact if the date could be in a wrong format or represent an invalid date: 或使用TryParseExact,如果日期格式错误或表示无效的日期:

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
}

There is no DateTime2 in C#, just DateTime: C#中没有DateTime2,只有DateTime:

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

If what you are looking for is converting datetime2 SQL data type to .NET data type, check this answer: 如果您要查找的是将datetime2 SQL数据类型转换为.NET数据类型,请检查以下答案:

Conversion of a datetime2 data type to a datetime data type results out-of-range value 将datetime2数据类型转换为datetime数据类型会导致超出范围的值

It seems to suggest that the type is same DateTime though, the snippet in the answer: 似乎暗示类型是相同的DateTime ,答案中的代码段:

new DataColumn("myDate", typeof(DateTime))

I assume if you are using a DataReader, you can treat the value as DateTime also, or maybe a DateTimeOFfset if DateTime . 我假设如果您使用的是DataReader,那么您也可以将该值视为DateTime ,或者将DateTimeOFfset视为DateTime

If you are using an ORM, it will depend on the ORM used. 如果您使用的是ORM,则取决于所使用的ORM。 You might need to specify how you access your database if this still doesn't help. 如果仍然没有帮助,则可能需要指定如何访问数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM