Coder
Coder

Reputation: 3715

How do you convert the SqlDateTime value to .Net::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?

Upvotes: 9

Views: 32091

Answers (5)

Joel C
Joel C

Reputation: 5567

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

Upvotes: 17

Priyank
Priyank

Reputation: 10623

Try using SqlDateTime.op_Explicit() [Ref: http://msdn.microsoft.com/en-us/library/exzwfa5y%28v=VS.100%29.aspx AND http://msdn.microsoft.com/en-us/library/aa326475%28v=vs.71%29.aspx Also,

Try this DateTime orderDate = Convert.ToDateTime(sqlparam.Value.ToString());

Upvotes: 0

Sergey K
Sergey K

Reputation: 4114

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

Upvotes: 3

Widor
Widor

Reputation: 13275

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

Upvotes: 5

Badr
Badr

Reputation: 10658

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);
    }
}

Upvotes: 6

Related Questions