Link to home
Start Free TrialLog in
Avatar of TALJr
TALJr

asked on

How do you convert Excel Date type to DateTime in .NET?

am using the Office Primary Interop Assemblies (automation) to access an
Excel file from .NET and get cell contents. I'm using C#.

When I get the cell contents that contains an Excel Date value, I am having
trouble converting from the object variable type to DateTime.
The following error is displayed:

               The specified cast is invalid.

Here's the code with error:

Range rng = (Range)oSheet.get_Range("A4", Type.Missing);
System.Object myvalue = rng.Cells.Value2; //Assign it to an object var
DateTime dt = (DateTime)myvalue;

So how do I cast the retrieved cell contents to .NET DateTime?
Avatar of Hitesh Manglani
Hitesh Manglani
Flag of India image

Avatar of TALJr
TALJr

ASKER

How does this apply to what I described?
It looks like it solves a problem different from what I asked.
you can parse the input string from the excel file as described in the link
Avatar of David H.H.Lee
Dear TALJr,
You can write your own custom format accordingly regarding the datetime that retrieved from cell content. Anyway, you can amend it based on the cell value that you retrieved.
eg:
//myvalue.ToString() = 2007-7-26 1:00:PM <-- your cell content value for example.
DateTime dt=Format(CDate("2007-7-26 1:00:PM"), "dd,MM yyyy hh:mm:tt")
For more details regarding custom format date, you can check here:
http://www.dotnetspider.com/qa/Question23642.aspx
Avatar of TALJr

ASKER

The myvalue.ToString()  value is not even close to the format you have given as an example. I don't have it right now( (I'm out of my office) but it is a large integer: something like  127879.
Would this be days after some start date? It is definitely not seconds or milliseconds.

This is not .NET DateTIme, but Excel Date type.

-TALJr

ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial