Format datetime string

11,561

Solution 1

parse the string and reformat it via strftime:

string = 'Wed, 26 May 2017 14:00:00 +0800'

Time.parse(string).strftime('%F %T %z')
#=> "2017-05-26 14:00:00 +0800"

Solution 2

Use strftime to format date in ruby.

OR

Run Time.now

2017-05-22 15:56:51 +0530

OR

Try below code:

n="Wed, 26 May 2017 14:00:00 +0800"
m=n.to_datetime
m.strftime("%Y-%m-%d %H:%M:%S %z")

output: "2017-05-26 14:00:00 +0800"

Solution 3

require "time"

Time.parse("Wed, 26 May 2017 14:00:00 +0800").to_s
# => "2017-05-26 14:00:00 +0800"

Time.parse("Wed, 26 May 2017 14:00:00 +0800").inspect
# => "2017-05-26 14:00:00 +0800"
Share:
11,561

Related videos on Youtube

Giovani
Author by

Giovani

Updated on June 04, 2022

Comments

  • Giovani
    Giovani almost 2 years

    I need my string "Wed, 26 May 2017 14:00:00 +0800" to be in format 2017-05-26 14:00:00 +0800 (it's ok to keep it as a string but not mandatory). What's the quickest way?

    • spickermann
      spickermann almost 7 years
      Is your input really the String or an instance of Time or DateTime? Why do you need that output (there might be better formats iso8601)?
    • sawa
      sawa almost 7 years
      It is not clear what you mean by "keep it as a string but not mandatory".
    • deniz
      deniz about 6 years
      Possible duplicate of Rails formatting date
  • sawa
    sawa almost 7 years
    Not sure. Hahaha.