olleh
olleh

Reputation: 1277

How to convert integer to unsigned 64-bit integer

I'm converting this code from C# to Ruby:

C# Code

DateTime dtEpoch = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc); 
string strTimeStamp = Convert.ToUInt64((DateTime.UtcNow - dtEpoch).TotalSeconds).ToString();

Ruby Code

now = Time.now.utc
epoch = Time.utc(1970,01,01, 0,0,0)
time_diff = ((now - epoch).to_s).unpack('Q').first.to_s            

I need to convert the integer into an unsigned 64-bit integer. Is unpack really the way to go?

Upvotes: 3

Views: 1331

Answers (2)

Aetherus
Aetherus

Reputation: 8888

In short, Time.now.to_i is enough.

Ruby internally stores Times in seconds since 1970-01-01T00:00:00.000+0000:

Time.now.to_f  #=> 1439806700.8638804
Time.now.to_i  #=> 1439806700

And you don't have to convert the value to something like ulong in C#, because Ruby automatically coerces the integer type so that it doesn't fight against your common sence.

A bit verbose explanation: ruby stores integers as instances of Fixnum, if that number fits the 63-bit size (not 64-bit, weird huh?) If that number exceeds that size, ruby automatically converts it to a Bignum, which has an arbitrary size.

Upvotes: 0

Mihai Dinculescu
Mihai Dinculescu

Reputation: 20033

I'm not really sure what is the returned value for your code, but it sure ain't seconds since epoch.

Ruby stores dates and times internally as seconds until epoch. Time.now.to_i will return exactly what you're looking for.

require 'date'

# Seconds from epoch to this very second
puts Time.now.to_i

# Seconds from epoch until today, 00:00
puts Date.today.to_time.to_i

Upvotes: 2

Related Questions