I have a scenario where i h开发者_C百科ave 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.
精彩评论