How do I convert a 'Fixnum' to a date in Rails 3.1.3? - ruby-on-rails

I am trying to display this output, as a date:
1296524384
But when I call .to_date on it, I am getting this error:
undefined method `to_date' for 1296524384:Fixnum

You can just do:
the_time = Time.at(1296524384)
That gives you:
2011-01-31 20:39:44 -0500
By the way, 1296524384 is referred to as UNIX or epoch time. It measures the number of seconds elapsed since January 1, 1970.
To format it a bit better, you can use Ruby's strftime method.
the_time = Time.at(1296524384).strftime("The date is %m/%d/%Y")
More info here: http://apidock.com/ruby/DateTime/strftime

Related

Rails - Convert time to string

This is the time format I want to convert
time = Time.parse('2020-07-02 03:59:59.999 UTC')
#=> 2020-07-02 03:59:59 UTC
I want to convert to string in this format.
"2020-07-02T03:59:59.999Z"
I have tried.
time.strftime("%Y-%m-%dT%H:%M:%S.999Z")
Is this correct? Any better way?
You can just use Time#iso8601 with the desired number of fraction digits as an argument:
time = Time.current.end_of_hour
time.iso8601(3) #=> "2020-07-01T10:59:59.999Z"
If you want to handle the output format explicitly via strftime, there are some things to keep in mind:
Instead of hard-coding 999, you should use %L to get the actual milliseconds:
time = Time.parse('2020-07-02 03:59:59.999 UTC')
#=> 2020-07-02 03:59:59 UTC
time.strftime('%Y-%m-%dT%H:%M:%S.%LZ')
#=> "2020-07-02T03:59:59.999Z"
Use combinations for common formats, e.g. %F for %Y-%m-%d and %T for %H:%M:%S:
time.strftime('%FT%T.%LZ')
#=> "2020-07-02T03:59:59.999Z"
If you are dealing with time zones other than UTC (maybe your machine's local time zone), make sure to convert your time instance to utc first:
time = Time.parse('2020-07-02 05:59:59.999+02:00')
#=> 2020-07-02 05:59:59 +0200
time.utc
#=> 2020-07-02 03:59:59 UTC
time.strftime('%FT%T.%LZ')
#=> "2020-07-02T03:59:59.999Z"
or to use %z / %:z to append the actual time zone offset:
time = Time.parse('2020-07-02 05:59:59.999+02:00')
time.strftime('%FT%T.%L%:z')
#=> "2020-07-02T05:59:59.999+02:00"
For APIs you should use utc.iso8601:
> timestamp = Time.now.utc.iso8601
=> "2015-07-04T21:53:23Z"
See:
https://thoughtbot.com/blog/its-about-time-zones#working-with-apis

erlang - return time in utc format

How to return time in RFC 3339 format (2014-06-01T12:00:00Z). I read docs about calendar module, but there was no explanation how to generate time format like this. My program should work in different time zones, so please give me advices.
The Erlang Central page Converting Between struct:time and ISO8601 Format has this example:
Unfortunately, no Erlang libraries provide this functionality. Luckily, the native Erlang date and time formats are very easy to format for display or transmission, even in ISO-8601 format:
-module(iso_fmt).
-export([iso_8601_fmt/1]).
iso_8601_fmt(DateTime) ->
{{Year,Month,Day},{Hour,Min,Sec}} = DateTime,
io_lib:format("~4.10.0B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B",
[Year, Month, Day, Hour, Min, Sec]).
format_iso8601() ->
{{Year, Month, Day}, {Hour, Min, Sec}} =
calendar:universal_time(),
iolist_to_binary(
io_lib:format(
"~.4.0w-~.2.0w-~.2.0wT~.2.0w:~.2.0w:~.2.0wZ",
[Year, Month, Day, Hour, Min, Sec] )).
Using the above module:
1> {{Year,Month,Day},{Hour,Min,Sec}} = erlang:localtime().
{{2004,8,28},{1,19,37}}
2> io:fwrite("~s\n",[iso_fmt:iso_8601_fmt(erlang:localtime())]).
2004-08-28 01:48:48
To make it output time in UTC, just pass it the return value of erlang:universaltime() instead of erlang:localtime().

Decoding the expiry date of a JavaScript Web Token (JWT)?

I am unable to understand the expiry date format of the JWT embedded in my application.
For example: 1473912000
What does this translate to? 1473912000 ms, some x date? Any help will be appreciated!
Like James has pointed out:
The number is the number of seconds since Jan 1 1970.
This is converted into the Date object in a quite straight-forward way (the *1000 part is here because in JS main time unit is millisecond):
const expiryDate = new Date(1473912000*1000);
Then you can use any Date method you please.
Likewise, in Ruby you can use Time.at(1473912000) to create a new Time instance like Maxim has shown.
The number is the number of seconds since Jan 1 1970. It is commonly used on unix systems to represent time. Your time is 2016-09-15 04:00 (UTC)
To convert you can try a web based system http://www.unixtimestamp.com/index.php
This is UNIX time in seconds:
➜ ~ irb
2.2.0 :001 > Time.at(1473912000)
=> 2016-09-15 07:00:00 +0300

Getting "argument out of range" when trying to turn a duration into milliseconds in Rails 4

I’m using Rails 4.2.4. I have the below method for converting a time (duration) to milliseconds …
Time.parse(convert_to_hrs(duration)).seconds_since_midnight * 1000
in which the method “convert_to_hrs” is defined as
def convert_to_hrs(string)
case string.count(':')
when 0
'00:00:' + string.rjust(2, '0')
when 1
'00:' + string
else
string
end
end
However, if the duration is something really big (e.g. “34:13:00” -- read: 34 hours, 13 minutes, and zero seconds), the above fails with the error
Error during processing: argument out of range
/Users/mikea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/time.rb:302:in `local'
/Users/mikea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/time.rb:302:in `make_time'
/Users/mikea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/time.rb:366:in `parse'
/Users/mikea/Documents/workspace/myproject/app/services/my_service.rb:25:in `block in process_page_data'
/Users/mikea/Documents/workspace/myproject/app/services/my_service.rb:22:in `each'
/Users/mikea/Documents/workspace/myproject/app/services/my_service.rb:22:in `process_page_data'
How do I rewrite my first line to accurately convert duration into milliseconds?
If you know you're always going to be using a hours:minutes:seconds format, but the number in each field isn't guaranteed to be inside the 'normal' range (e.g. 0-23 for hours, 0-59 for minutes, etc), then you're probably best off doing it 'manually' using something like this:
def duration_in_milliseconds(input)
h, m, s = input.split(':').map(&:to_i)
(h.hours + m.minutes + s.seconds) * 1000
end
puts duration_in_milliseconds('34:13:00') #=> 123180000
Note that this only works with ActiveSupport, but you have that, since you've specified Rails. Also, this assumes you're always getting all three terms (e.g. 5 seconds is 00:00:05). The full setup that accepts shorter strings as well would want to also use your convert_to_hrs method.
Note also that this works even if formatting isn't strictly 'time-like', as long as you have consistent colons as seperators:
puts duration_in_milliseconds('1:1:5') #=> 3665000
The Numeric#hours, Numeric#minutes and Numeric#seconds methods are provided by ActiveSupport, as part of active_support/core-ext/time.rb. They aren't particularly documented, but they return ActiveSupport::Duration objects, which have fancy methods for interacting with Time and Date issues like 5.days.ago, but when treated as an integer are effectively a number of seconds.
Time.parse is throwing error, becuase values you passing in duration variable is out of range.
For Ex:
Time.parse(convert_to_hrs('59:59')) as per your written code, it's return 2016-07-27 00:59:59 +0530
Here the value 59:59 consider as minutes:seconds, so if you pass the value 60:60 then it will raise the error argument out of range
Here is the official documentation for parse method of Time
Hope this will help you.

How to convert a long to date?

I have a long value in Rails, 134740800, which is the number of milliseconds since the epoch.
How do I convert that to a date in mm-dd-yyyy format?
I figure the formatting would be done with something like strftime but I can't seem to find the right method to convert the long into a valid date.
secs = 134740800/1000 # millisecs / 1000
t = Time.at(secs)
t.strftime("%m-%d-%Y")
Output
"01-02-1970"
Try this:
require 'date'
DateTime.strptime("1318996912",'%s')
I assume you mean seconds since the epoch.
Time.at seconds_since_epoch
You can also pass a float. If you have milliseconds, divide by 1000.0 first.
You can then call strftime on the returned Time object.
Use Time.at:
irb(main):003:0> Time.at(134740800)
=> Tue Apr 09 08:00:00 -0400 1974
This is an advisory... It's often a good idea to look at how fast some answers run. Here's a simple benchmark:
require 'benchmark'
require 'date'
SECS = 134740800
LOOPS = 1_000_000
puts Time.at(SECS).strftime('%m-%d-%Y')
puts Date.strptime(SECS.to_s, '%s').strftime('%m-%d-%Y')
Benchmark.bm(14) do |x|
x.report('Time.at:') { LOOPS.times { Time.at(SECS) }}
x.report('Date.strptime:') { LOOPS.times { Date.strptime(SECS.to_s, '%s') }}
end
And the output is:
04-09-1974
04-09-1974
user system total real
Time.at: 0.370000 0.020000 0.390000 ( 0.392761)
Date.strptime: 6.320000 0.050000 6.370000 ( 6.373248)

Resources