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"
Related
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
I'm trying to convert a Ruby Date object to a string. The format of the date is: Sun, 15 Sep 2013
However, when I convert it to a string using #to_s it gives me the following: "2013-09-15"
Instead, I want it to become: "Sun, 15 Sep 2013"
Use Date#strftime there are so many options
require 'date'
date = Date.parse("Sun, 15 Sep 2013") # => #<Date: 2013-09-15 ((2456551j,0s,0n),+0s,2299161j)>
date.strftime("%a, %d %b %Y") # => "Sun, 15 Sep 2013"
strftime works well, however, if you find that you're using the same format in multiple places, you will find using the Rails Date#to_formatted_s method a more appropriate option. You can use the built-in formats:
date.to_formatted_s(:short)
date.to_formatted_s(:long)
or, you can create your own formats, adding them to Date::DATE_FORMATS:
Date::DATE_FORMATS[:my_format] = '%a, %d %b %Y'
date.to_formatted_s(:my_format)
This will keep you from spreading formatting strings throughout your app.
I want to be able to parse a Time from a string in Ruby (1.8.7), where the string does not contain any time zone information. I would like to treat the string as though it were in any of a number of time zones specified in this type of format: 'America/New_York'.
Time string example:
'2010-02-05 01:00:01'
I have spent quite a while trying to figure this one out.
I did find a similar question, but its answer does not apply in my case: How do I get Ruby to parse time as if it were in a different time zone?
The problem with the above solution is that my time zones cannot all be represented in the 3-letter format supported by Time.parse (http://www.ruby-doc.org/stdlib-1.8.7/libdoc/time/rdoc/classes/Time.html#M004931).
Is there a good way to accomplish what I'm trying to do here?
Edit: Made my answer actually appear as an answer.
require 'active_support/all'
time = ActiveSupport::TimeZone.new('UTC').parse('2010-02-05 01:00:01')
puts time
puts time.in_time_zone('EST')
Here's what I came up with using the tzinfo gem as suggested, though it seems rather complicated and unintuitive to me. As an end result I get the time parsed as though it were in the time zone I wanted, though represented by a Time object in UTC. I can also display it in the time zone I want using tzinfo's strftime:
jruby-1.6.1 :003 > time = '2010-05-01 01:00:00'
=> "2010-05-01 01:00:00"
jruby-1.6.1 :004 > tz = TZInfo::Timezone.get('America/New_York')
=> #<TZInfo::DataTimezone: America/New_York>
jruby-1.6.1 :005 > time += ' UTC'
=> "2010-05-01 01:00:00 UTC"
jruby-1.6.1 :006 > time = Time.parse(time)
=> Sat May 01 01:00:00 UTC 2010
jruby-1.6.1 :007 > time = tz.local_to_utc(time)
=> Sat May 01 05:00:00 UTC 2010
jruby-1.6.1 :010 > tz.strftime('%Y-%m-%d %H:%M:%S %Z', time)
=> "2010-05-01 01:00:00 EDT"
I believe this will suit my needs, but I wonder if I can get the Time to actually be in the timezone above (instead of just UTC).
You have two options the way I see it. On the one hand you could map the format you wish to use in an array (or any other structure you wish) to the 3-letter format used by Time.parse.
The other option is using the tzinfo gem as specified by my which seems to do the job quite nicely.
>> tz = TZInfo::Timezone.get("America/New_York")
=> #<TZInfo::DataTimezone: America/New_York>
>> tz.now
=> Thu Jul 07 16:29:13 UTC 2011
>> tz = TZInfo::Timezone.get("Europe/Rome")
=> #<TZInfo::DataTimezone: Europe/Rome>
>> tz.now
=> Thu Jul 07 22:30:03 UTC 2011
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
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