0

I have a function that convert ticks to time_t format

 long ticks = DateTime.Now.Ticks;

       long tt = GetTimeTSecondsFrom(ticks);

  long GetTimeTSecondsFrom(long ticks)
    {
        DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        return (long) (new DateTime(ticks) - epoch).TotalSeconds;
    }

Now i am confused how to convert it back to ticks with some mathematical formula and not with a function.

Any suggestions...??

thanks

Let me take a general case and explain. DateTime.Now.Ticks give me a value 633921719670980000 which is in tics

then i convert this in time_t with the above function and get tt = 1256575167

now i want to convert this back to 633921719670980000. for this i need a formula

user175084
  • 4,550
  • 28
  • 114
  • 169

3 Answers3

3

The answer was given as a comment to your original question regarding converting ticks to time_t.

DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return TimeSpan.FromSeconds(time_t_value).Ticks + epoch.Ticks;
Community
  • 1
  • 1
Jason Berkan
  • 8,734
  • 7
  • 29
  • 39
  • it gives an error 'System.TimeSpan does not contain a definition for 'TotalTicks'and no extension method'TotalTicks........ – user175084 Oct 26 '09 at 22:03
  • I just copied and pasted from the original comment. It is .Ticks, not .TotalTicks, which is easily discoverable using the Intellisense. I have updated the answer. – Jason Berkan Oct 26 '09 at 22:06
  • so there is no formula to do this.... i ask this because i need to use it in my databasequery.... i have store in time_t then convert it to ticks and diplay a date in a particular format which i get by manipulating the ticks... – user175084 Oct 26 '09 at 22:12
  • You shouldn't need a formula in your database. Just ensure that you always convert from ticks to time_t before sending it to the database and convert form time_t to ticks after loading it from the database. – Jason Berkan Oct 26 '09 at 22:17
2

The date1970-01-01 00:00:00 Zis exactly 62,135,596,800 seconds (621,355,968,000,000,000 ticks), so to convert aDateTimetick count into atime_tvalue you could just scale it (divide by 10,000,000) to get seconds, and then subtract that offset.

To go the other way, do the reverse: add the offset seconds to thetime_tvalue, then scale it (multiply by 10,000,000) to get ticks.

David R Tribble
  • 11,918
  • 5
  • 42
  • 52
0

From the MSDN documentation:

A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.

So, a function to convert seconds to ticks would look something like:

long GetTicksFromSeconds(long seconds)
{
    return seconds * 10000000;
}
pmarflee
  • 3,428
  • 20
  • 21
  • this will not give me the value i want... please have a look at my edited part to get the clear picture.. thanks – user175084 Oct 26 '09 at 20:48