开发者

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 开发者_Go百科should be one, right?


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


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


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜