Skip to content

Instantly share code, notes, and snippets.

@morkevicius
Forked from chancancode/gist:2830878
Last active July 13, 2016 21:54
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save morkevicius/10549920 to your computer and use it in GitHub Desktop.
Save morkevicius/10549920 to your computer and use it in GitHub Desktop.
.net ticks to ruby time, ruby time to ticks 1.8.7
class Time
# See http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx
# https://gist.github.com/chancancode/2830878
TICKS_SINCE_EPOCH = -(Time.utc(0001, 01, 01).to_i * 10000000)
def to_ticks
utc.to_i * 10000000 + TICKS_SINCE_EPOCH # ruby 1.8.7 doesn't support nano seconds so we're ok without it
# to_i * 10000000 + nsec / 100 - TICKS_SINCE_EPOCH
# <seconds from 1970-01-01 multiplied by 10 000 000> result is ticks + <self nsec which by default would be skipped>/100 result is ticks + ticks from 0001-01-01
end
def self.ticks_to_date_time(ticks)
time_at_ticks =Time.use_zone('UTC') do
Time.zone.at(seconds_from_christ = (ticks- TICKS_SINCE_EPOCH)/10000000 )
end
# to_i * 10000000 / 100 - TICKS_SINCE_EPOCH # ruby 1.8.7 doesn't support nano seconds so we're ok without it
# to_i * 10000000 + nsec / 100 - TICKS_SINCE_EPOCH
# <seconds from 1970-01-01 multiplied by 10 000 000> result is ticks + <self nsec which by default would be skipped>/100 result is ticks + ticks from 0001-01-01
end
end
# nanosecond = 1/1 000 000 000 s
# 1s = 10 000 000 ticks
#
# A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.
# The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001,
# which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.
@damonjmurray
Copy link

Do you think TICKS_AT_EPOCH is a better name for that constant? The word 'since' implies (at least to me) that the value will change with every passing moment.

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