简体   繁体   中英

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. 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#? Im using .Net 4

You could use the ParseExact method:

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:

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:

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:

Conversion of a datetime2 data type to a datetime data type results out-of-range value

It seems to suggest that the type is same DateTime though, the snippet in the answer:

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 .

If you are using an ORM, it will depend on the ORM used. You might need to specify how you access your database if this still doesn't help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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