Home > database >  How to get UTC date string in Ruby
How to get UTC date string in Ruby

Time:05-04

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?

CodePudding user response:

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"

CodePudding user response:

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"
  •  Tags:  
  • ruby
  • Related