Easy way to generate http date (GMT) string in ruby - ruby

I need to generate an HTTP (GMT) date string in Ruby. This is because of a requirement of an API that I'm consuming.
What is an easy (out of the box) way to generate it?

I found that Ruby comes with a method for the Time class out of the box for this:
Time.now.httpdate # => "Thu, 06 Oct 2011 02:26:12 GMT"
The time class also supports the following methods
Time.now.iso8601 # => "2011-10-05T22:26:12-04:00"
Time.now.rfc2822 # => "Wed, 05 Oct 2011 22:26:12 -0400"
Source: http://ruby-doc.org/stdlib-2.0.0/libdoc/time/rdoc/Time.html#class-Time-label-Converting+to+a+String

does Time.now.getgm work for you?
Time.now.gmt? #=> fale
Time.now.getgm.gmt? #=> true

Related

How to get UTC date string in Ruby

In JS you can do this:
var d = new Date()
d.toUTCString()
// Tue, 03 May 2022 09:21:04 GMT
Is there an equivalent in Ruby?
In Ruby's standard library, there are extensions to the core Time class which add some convenience methods, including multiple common ways to format time objects.
In your case, you apparently want an string formatted according to the rules defined in RFC 2616, Section 3.3.1 for use in the HTTP protocol.
require 'time'
utc_time = Time.now.utc
utc_time.httpdate
# => "Tue, 03 May 2022 10:14:37 GMT"
If you have control over the way the data is read and are not strictly bound to historic standards, you may however try to use the ISO 8601 format instead which is easier to parse and has the added benefit of sorting correctly in the usual alphabetical way. This time format (or slight variants thereof) are often used in e.g. JSON or YAML files:
require 'time'
utc_time = Time.now.utc
utc_time.iso8601
# => "2022-05-03T10:14:37Z"
Time.now.utc
=> 2022-05-03 09:54:04 UTC
Or if you want the same format:
Time.now.utc.strftime "%a, %d %b %Y %H:%M:%S GMT"
=> "Tue, 03 May 2022 09:54:12 GMT"

Ruby Convert Date

I have a page that is returning this as a date new Date(1357106400000) (which I believe is Javascript).
How do I convert that using Ruby. I've tried:
Date.new(1357106400000)
DateTime.new(1357106400000)
and many others, but I can't get the correct date to display.
The date returned should be 12/09/2012
I believe you've got the time in milliseconds since the epoch, and the function you're looking for is Time#at. But you need to down-convert into seconds before calling. For example:
[holt#Michaela ~]$ irb
irb(main):001:0> Time.at(1357106400000)
=> Wed Dec 28 00:00:00 +0000 44974
irb(main):002:0> Time.at(1357106400000 / 1000)
=> Wed Jan 02 06:00:00 +0000 2013
irb(main):003:0>
Not the exact day you thought it was, but probably still correct. Hope that helps!
In Javascript:
> new Date(1357106400000)
Wed Jan 02 2013 06:00:00 GMT+0000 (GMT Standard Time)
In Ruby:
> require 'date'
> DateTime.strptime("1357106400000", "%Q")
=> #<DateTime: 2013-01-02T06:00:00+00:00 ((2456295j,21600s,0n),+0s,2299161j)>

How to create time objects in GMT

We use the Time.now function to fetch the time corresponding to a certain timezone. What would be the simplest way to create time object in GMT and how do I translate this into a certain timezone/locale (e.g. PST/en_US, JST, ja_JP)
Time.now.utc for a first part and tzinfo for a 2nd
Time.now.gmtime will give you the gmt.
Use I18n to localize it
eg : I18n.localize(time, :format => :date_format_MMM_D_YYYY)
For GMT, use
Time.now.utc # it returns UTC time => "2011-12-14 07:05:18 UTC"
For local time, you can use active_support/time. You require the gem and use the in_time_zone method
require 'active_support/time'
Time.now.in_time_zone('<time_zone>')
eg:
Time.now.in_time_zone('Kolkata') # It returns time in IST => Wed, 14 Dec 2011 12:39:07 IST +05:30
Time.now.in_time_zone('Paris') # It returns French time => Wed, 14 Dec 2011 08:13:40 CET +01:00

How do I get Ruby to parse time as if it were in a different time zone?

I'm parsing something like this:
11/23/10 23:29:57
which has no time zone associated with it, but I know it's in the UTC time zone (while I'm not). How can I get Ruby to parse this as if it were in the UTC timezone?
You could just append the UTC timezone name to the string before parsing it:
require 'time'
s = "11/23/10 23:29:57"
Time.parse(s) # => Tue Nov 23 23:29:57 -0800 2010
s += " UTC"
Time.parse(s) # => Tue Nov 23 23:29:57 UTC 2010
credit from https://rubyinrails.com/2018/05/30/rails-parse-date-time-string-in-utc-zone/,
Time.find_zone("UTC").parse(datetime)
# => Wed, 30 May 2018 18:00:00 UTC +05:30
If your using rails you can use the ActiveSupport::TimeZone helpers
current_timezone = Time.zone
Time.zone = "UTC"
Time.zone.parse("Tue Nov 23 23:29:57 2010") # => Tue, 23 Nov 2010 23:29:57 UTC +00:00
Time.zone = current_timezone
It is designed to have the timezone set at the beginning of the request based on user timezone.
Everything does need to have Time.zone on it, so Time.parse would still parse as the servers timezone.
http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html
Note: the time format you have above was no longer working, so I changed to a format that is supported.
If you are using ActiveSupport [from Rails, e.g], you can do this:
ActiveSupport::TimeZone["GMT"].parse("..... date string")
Another pure Ruby (no Rails) solution if you don't want/need to load ActiveSupport.
require "time"
ENV['TZ'] = 'UTC'
Time.parse("2019/10/01 23:29:57")
#=> 2019-10-01 23:29:57 +0000
An aliter to #Pete Brumm's answer without Time.zone set/unset
Time.zone.parse("Tue Nov 23 23:29:57 2010") + Time.zone.utc_offset
Without rails dependencies: Time parses in local time but DateTime parses in UTC. Then you can transform it to a Time class if that's what you want:
require 'date'
DateTime.parse(string_to_parse).to_time
Rails adds utc method on datetime objects to return the utc time:
Time.parse('10:10').utc

convert String to DateTime

I need to parse following String into a DateTime Object:
30/Nov/2009:16:29:30 +0100
Is there an easy way to do this?
PS: I want to convert the string above as is. The colon after the year is not a typo. I also want to solve the problem with Ruby and not RoR.
Shouldn't this also work for Rails?
"30/Nov/2009 16:29:30 +0100".to_datetime
DateTime.strptime allows you to specify the format and convert a String to a DateTime.
I have had success with:
require 'time'
t = Time.parse(some_string)
This will convert the string in date to datetime, if using Rails:
"05/05/2012".to_time
Doc Reference: https://apidock.com/rails/String/to_time
I used Time.parse("02/07/1988"), like some of the other posters.
An interesting gotcha was that Time was loaded by default when I opened up IRB, but Time.parse was not defined. I had to require 'time' to get it to work.
That's with Ruby 2.2.
convert string to date:
# without timezone
DateTime.strptime('2012-12-09 00:01:36', '%Y-%m-%d %H:%M:%S')
=> Sun, 09 Dec 2012 00:01:36 +0000
# with specified timezone
DateTime.strptime('2012-12-09 00:01:36 +8', '%Y-%m-%d %H:%M:%S %z')
=> Sun, 09 Dec 2012 00:01:36 +0800
refer to:
https://ruby-doc.org/stdlib-3.1.1/libdoc/date/rdoc/Date.html
in Ruby 1.8, the ParseDate module will convert this and many other date/time formats. However, it does not deal gracefully with the colon between the year and the hour. Assuming that colon is a typo and is actually a space, then:
#!/usr/bin/ruby1.8
require 'parsedate'
s = "30/Nov/2009 16:29:30 +0100"
p Time.mktime(*ParseDate.parsedate(s)) # => Mon Nov 30 16:29:30 -0700 2009
You can parse a date time string with a given timezone as well:
zone = "Pacific Time (US & Canada)"
ActiveSupport::TimeZone[zone].parse("2020-05-24 18:45:00")
=> Sun, 24 May 2020 18:45:00 PDT -07:00

Resources