Convert BigInt value in SQL to datetime in c#
I usually use the SQL function below to convert bigint in sql to datetime in SQL Server 2005.
DECLARE @datetime AS bigint, @day AS int, @ms AS int
SET @datetime = 129471410567460000
SET @ms = (@datetime / CAST(10000 AS bigint)) % 86400000
SET @day = @datetime / CAST(864000000000 AS bigint) - 109207
SELECT DATEADD(ms,@ms, DATEADD(day, @day, 0))
How do i do it using c# ? I am able to read in time value (129471410567460000) from the SQL server and want to convert to datetime. The datetime will be us开发者_JAVA百科ed in a c# application.
Cheers
Are you trying to convert a bigint in SQL Server to a datetime in C#? If so, you would do something like:
var tickValue = 129471410567460000;
var datetime = new DateTime( tickValue );
If however, you are tying to convert a bigint value in SQL Server to a datetime value in SQL Server then look at the following link:
Convert .NET Ticks to SQL Server DateTime
If you are trying mimic your exact logic (how you are getting that tick value is its own mystery):
var tickValue = 129471410567460000;
var ms = ( tickValue / 10000 ) % 86400000;
var day = tickValue / 864000000000 - 109207;
var startDate = new DateTime( 1900, 1, 1 );
var resultDateTime = startDate.AddMilliseconds( ms ).AddDays( day );
The trick to this logic is the start date. In SQL Server, day zero = '1900-01-01' even though DateTime values can store values going back to 1753.
In comments, you mentioned that the SQL method was posted in a forum. It is crucial that you know the method used to calculate the bigint value. The forum seems to suggest that this value is a Win32 FILETIME structure: that stores the date as 100-nanosecond intervals since 1601. If that is the case, the code you would use in C# is:
var startDate = new DateTime( 1601, 1, 1 );
var resultDateTime = startDate.AddTicks( tickValue );
You will note that this value returns 2003-05-14 4:51:56 PM
which is the approximate date and time of the forum thread.
Solution is
DateTime.FromFileTimeUtc()
You could make it a stored procedure, then call that from C#.
Try this:
long datetime = 129471410567460000;
int ms = (int)((datetime / 10000) % 86400000);
int day = (int)(datetime / 864000000000L) - 109207;
DateTime dt = DateTime.MinValue.AddDays(day).AddMilliseconds(ms);
public DateTime ConvertLongFormate2DateTime(long iDatelongValue)
{
try
{
var iSecondCal = (iDatelongValue / 1000 + 8 * 60 * 60);
var startDate = new DateTime(1970, 01, 01);
DateTime resultDateTime = startDate.AddSeconds(iSecondCal);
return resultDateTime;
}
catch (Exception)
{
throw;
}
}
精彩评论