The default formatting is not very useful, in my opinion. I prefer ISO8601 as it's sortable, relatively compact and widely recognized:
>> require 'time'
=> true
>> Time.now.utc.iso8601
=> "2011-07-28T23:14:04Z"
You could use: Time.now.to_i
.
What good is a timestamp with its granularity given in seconds? I find it much more practical working with Time.now.to_f
. Heck, you may even throw a to_s.sub('.','')
to get rid of the decimal point, or perform a typecast like this: Integer(1e6*Time.now.to_f)
.
time = Time.zone.now()
It will work as
irb> Time.zone.now
=> 2017-12-02 12:06:41 UTC
Time.utc(2010, 05, 17)
Usually timestamp has no timezone.
% irb
> Time.now.to_i == Time.now.getutc.to_i
=> true
The proper way is to do a Time.now.getutc.to_i
to get the proper timestamp amount as simply displaying the integer need not always be same as the utc timestamp due to time zone differences.
if you need a human-readable timestamp (like rails migration has) ex. "20190527141340"
Time.now.utc.to_formatted_s(:number) # using Rails
Time.now.utc.strftime("%Y%m%d%H%M%S") # using Ruby
Source: Stackoverflow.com