How to convert a date represented as a long in database

R

Richard

Hi all,

Hope everybody is having an OK monday?!!?

Quick question, I have a database in which the dates are stored as
longs. I think the original program was VB and the dates were just
cast to long before being saved to the database.

I now need to convert these long values back into datetime values.

I could do this in SQL by doing:
PRINT Convert(varchar, Convert(datetime, Convert(int, '38875')-2))

but was wondering if there was a C# way?

Cheers,

OO
 
G

Guest

Provided VB and .NET use the same starting date, which is likely, there is an
overload on the DateTime constructor that accepts a long. If not, set up a
DateTime with the starting date for VB and add the long in a timespan object.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

***************************
Think Outside the Box!
***************************
 
N

Nicholas Paldino [.NET/C# MVP]

You have to be careful here, because you have to make sure that SQL
Server and .NET use the same starting date (if the OP is pulling the values
form the database first before converting).
 
C

Chris Jobson

Richard said:
Quick question, I have a database in which the dates are stored as
longs. I think the original program was VB and the dates were just
cast to long before being saved to the database.

I now need to convert these long values back into datetime values.

I believe that the VB date is the number of days since 30th December 1899,
so the following ought to work (but I haven't tried it).

DateTime startDate = new DateTime(1899, 12, 30);
DateTime dateWanted = startdate.AddDays(valueFromDatabase);

Chris Jobson
 
J

Jianwei Sun

The System.DateTime has a constructor which takes a long value, is this
what you looking for?
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

I don't think so, DateTime start at midnight of year 1 , I bet VB does not,
the same thing with SQL, IIRC it's around 1899.


cheers,
 
R

Richard

Hi,

Thanks for your messages!

Although there is an overload for DateTime that accepts a long, this
will always throw an InvalidCastException according to MSDN.
I know VB went from 1899 Dec 30th whereas SQL starts at 1900 Jan 1 so I
would have to calculate for that. I think the timespan as suggested
above is the way to go.

Cheers all,

Richard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top