Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert the SqlDateTime value to .Net::DateTime

Tags:

c#

sql

datetime

Tried searching everywhere and no go.

The approach so far is DateTime dt = (DateTime)sqlparam.Value;. Which I can imagine can go wrong on different configurations, different SQL regional settings, different PC regional settings and so on. But then again, parsing value off SQL datetime string is even crazier idea.

Is there a working solution for this, it's .NET, there should be one, right?

like image 338
Coder Avatar asked Apr 13 '11 13:04

Coder


4 Answers

The SqlDateTime class has a property Value which is already of type DateTime. Why would any conversion be necessary? Just use the Value directly.

like image 58
Joel C Avatar answered Sep 30 '22 18:09

Joel C


using System;

class Program
{
    static void Main()
    {
    // Taken from MySQL: SELECT CURTIME()
    //                   SELECT TIME(...)
    string mySqlTime = "23:50:26";
    DateTime time = DateTime.Parse(mySqlTime);

    // Taken from MySQL: SELECT TIMESTAMP(...)
    string mySqlTimestamp = "2003-12-31 00:00:00";
    time = DateTime.Parse(mySqlTimestamp);
    Console.WriteLine(time);

    // Taken from MySQL: SELECT CURDATE()
    //                   SELECT DATE(...)
    string mySqlDate = "2008-06-13";
    time = DateTime.Parse(mySqlDate);
    Console.WriteLine(time);
    }
}
like image 23
Badr Avatar answered Sep 30 '22 19:09

Badr


I don't see what's wrong with explicitly casting it, that's how I'd do it.

If your problems are being caused by "different configurations, different SQL regional settings, different PC regional settings" then using a different conversion method won't help.

However, you might like to look at this new data type in SQL Server 2008: DateTimeOffset

like image 43
Widor Avatar answered Sep 30 '22 17:09

Widor


Just cast it to DateTime. If it's nullable, cast it to Nullable, which can also be written as "DateTime?".

DateTime? value = (DateTime?)resultSet["myDateColumn"];

look at the SqlDateTime Class

it has a Parse methods you can Parse you string into the SqlDateTime after cast into DateTime

like image 43
Serghei Avatar answered Sep 30 '22 19:09

Serghei