Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET DateTime to time_t in seconds

There is C code :

time1=((double)dt1-25569.0)*86400.0;

it's convert from TDateTime (VCL) to time_t format in seconds, so finally I need to get time_t format from .NET DateTime

about time_t :

It is almost universally expected to be an integral value representing the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC. This is due to historical reasons, since it corresponds to a unix timestamp, but is widely implemented in C libraries across all platforms.

So to get seconds in .NET I'm doing this (F#):

let seconds(dt : DateTime) =
    (dt.Ticks/10000000L)

or on C# (to use more popular C# tag) :

Int64 seonds(DateTime dt)
{ return (dt.Ticks/ ((Int64)10000000)); } 
// hope it works, but please correct if I mistaken

As far as I understand it's time from 12:00:00 Jan 1, 0001 UTC.

So to use time_t format I need to add 1970 years in seconds.

So final function must be (F#):

let seconds(dt : DateTime) =
    (dt.Ticks/10000000L) + 31536000*1970

C# :

Int64 seonds(DateTime dt)
{ return (dt.Ticks/ ((Int64)10000000)) + 31536000*1970; } 

I really afraid I made mistake here. Please examine this solution ! (check if this is done right)

Thank you

like image 337
cnd Avatar asked Aug 29 '11 07:08

cnd


1 Answers

try

 (dt - new DateTime (1970, 1, 1)).TotalSeconds

see

  • http://msdn.microsoft.com/en-us/library/system.timespan.totalseconds.aspx
  • http://msdn.microsoft.com/en-us/library/xcfzdy4x.aspx
like image 129
Yahia Avatar answered Sep 30 '22 04:09

Yahia