10

I am reading Excel worksheet data using C# and Microsoft.Office.Interop. The sheet contains some date values. When I am trying to read that value it is just giving the number (probably TimeSpan). I am having problem converting this number into DateTime.

Below is the code:

TimeSpan ts = TimeSpan.Parse(((Range)ws.Cells[4, 1]).Value2.ToString());

Where ws is Excel.WorkSheet.

Can anybody explain how should I convert this number (TimeSpan) into DateTime?

Thanks for sharing your valuable time.

Tim Barrass
  • 4,813
  • 2
  • 29
  • 55
IrfanRaza
  • 3,030
  • 17
  • 64
  • 89

4 Answers4

9

You could do the following

double d = double.Parse(((Range)ws.Cells[4, 1]).Value2.ToString());

DateTime conv = DateTime.FromOADate(d);
Dimi Takis
  • 4,924
  • 3
  • 29
  • 41
9

Use the following:

DateTime dt = new DateTime().Add( TimeSpan.FromMilliseconds( 1304686771794 ) )
GSerg
  • 76,472
  • 17
  • 159
  • 346
Ardian
  • 91
  • 1
  • 1
6

It all depends on what the number looks like ;p That is typically the offset in some interval, into some epoch - for example seconds since 1 Jan 1970. So try, for example:

var when = new DateTime(1970,1,1).AddSeconds(number);

and then try AddMilliseconds(number), AddTicks(number) etc until the date matches.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

This is just icing: Excel represents dates as OLE automation dates. These values are floating point numbers, the integer part of which is the number of days after midnight, 30 Dec 1899. Or before, if it's negative. Greco's answer gives you the best way to convert :)

Tim Barrass
  • 4,813
  • 2
  • 29
  • 55