Home > other >  Parse Time in Ruby
Parse Time in Ruby

Time:05-20

I'm trying to parse this date Wed, 17 Feb 2021 13:00:00 0100 into this 2021-02-17 13:00:00.000000000 0100.

And I've tried using this Time.strptime(current_time.to_s, '%Q'), (where current_time it's the date above) but I get 1970-01-01 01:00:02.021 0100

But I don't understand why I get another date, could you help me? Thanks!

CodePudding user response:

I'm trying to parse this date Wed, 17 Feb 2021 13:00:00 0100 [...]

You seem to already have an instance of Time: (or ActiveSupport::TimeWithZone which is Rails' drop-in replacement with better timezone support)

current_time = Time.current
#=> Thu, 19 May 2022 10:09:58.702560000 CEST  02:00

In this case, there's nothing to parse. You just have to format it via strftime the way you like:

current_time.strftime('%F %T.%N %z')
#=> "2022-05-19 10:09:58.702560000  0200"

Parsing is only needed when you have a string representation that you want to turn into a Time object, e.g.: (using Rails' Time.zone.parse variant)

time_string = 'Thu, 19 May 2022 10:09:58.702560000 CEST  02:00'

time_obj = Time.zone.parse(time_string)
#=> Thu, 19 May 2022 10:09:58.702560000 CEST  02:00

time_obj.class
#=> ActiveSupport::TimeWithZone
  • Related