Skip to content

Instantly share code, notes, and snippets.

@chancancode
Created May 29, 2012 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chancancode/2830878 to your computer and use it in GitHub Desktop.
Save chancancode/2830878 to your computer and use it in GitHub Desktop.
Ruby time to .NET ticks
class Time
# See http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx
TICKS_SINCE_EPOCH = Time.utc(0001,01,01).to_i * 10000000
def ticks
to_i * 10000000 + nsec / 100 - TICKS_SINCE_EPOCH
end
end
@chancancode
Copy link
Author

$ rvm use 1.9.3
Using /Users/godfrey/.rvm/gems/ruby-1.9.3-p125
$ irb
>> class Time
>>   # See http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx
?>   TICKS_SINCE_EPOCH = Time.utc(0001,01,01).to_i * 10000000
>> 
?>   def ticks
>>     to_i * 10000000 + nsec / 100 - TICKS_SINCE_EPOCH
>>   end
>> end
=> nil
>> 
?> Time.now.ticks
=> 634739243347336440
>> 

@mahhek
Copy link

mahhek commented Feb 24, 2013

Hi, I have two questions, kindly reply.

following are the steps:
rvm use 1.9.3
Using /usr/local/rvm/gems/ruby-1.9.3-p0

then rails c

then following things.

first, how can i get nsec for this statement? ,

to_i * 10000000 + nsec / 100 - TICKS_SINCE_EPOCH
I tried this Time.new.nsec, it gave me some string. So I tried to use this in following line and it gave me this error.

to_i * 10000000 + Time.new.nsec / 100 - TICKS_SINCE_EPOCH

then it says:

undefined local variable or method 'to_i' for main:Object

kindly guide me how to calculate ticks in ruby thanks a lot,
regards,
MK.

@morkevicius
Copy link

did some updates for 1.8.7, added some description for myself but maybe it would help somebody else https://gist.github.com/morkevicius/10549920

@jchannon
Copy link

Any improvements required for Ruby 2.5?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment