Barry said:
Hi
In a excel sheet processed through C#, i get a Date (11/6/2006) as 39027,
how do i convert this value to a DateTime (maybe as a string)
The Excel value is in days since Excel's base time, which is by default Jan
1, 1900 under Windows. The default for Mac Excel is Jan 2, 1904. This date
can be changed using the Tools/Options... menu item.
Because the date storage format in Excel is changeable, the most reliable
method to solve your problem is probably to convert the date to text in
Excel, and process the text in .NET using the DateTime.Parse or ParseExact
method. For example:
* In Excel, create a cell that references your data cell using the
formula =TEXT(A1, "mm/dd/yyyy") where you've replaced "A1" with the actual
cell containing your serial date. Feel free to use a different number
format string as needed (and of course, use the matching pattern in the .NET
parse method).
* In your .NET program:
DateTime dtResult = DateTime.ParseExact(strExcel, "MM/dd/yyyy",
null);
The assumption here is that "strExcel" contains the string value obtained
from Excel after converting the date to a string in Excel.
If you are absolutely sure that the base time will always be the same, then
in .NET you could set a DateTime structure to the base time you're using,
set a TimeSpan structure to contain the number obtained from Excel as Days
(minus one, because Excel's dates are one-based, not zero-based), and then
add that to the base time DateTime structure. If you want to preserve
fractional dates (that is, a specific time within a date), you'll have to
convert the fractional part to hours, minutes, seconds, etc. as desired.
IMHO, the easiest way to do that would be to convert the fractional part to
the smallest division you're interested in, and add that to the DateTime
structure. For example:
DateTime dtResult, dtBase = new DateTime(1900, 1, 1);
TimeSpan tsExcel = new TimeSpan((int)flExcelDays - 1, 0, 0, 0);
float flTime = flExcelDays - (int)flExcelDays;
// convert fraction of a day into seconds
tsExcel.Seconds += flTime * 24 * 60 * 60;
dtResult = dtBase + tsExcel;
Assumptions here are that flExcelDays contains the floating point value of
the serial date from Excel, and that you will use the resulting date in the
"dtResult" variable.
Hope that helps. I apologize in advance for any errors...I'm up way too
late to be posting code.
Pete