2

I'm learning Ruby on Rails and have dates with the format 20170802173300 witch is:

Mie, 02 Ago 2017 17:33:00 -0300.

How can I convert this to ?

2017-08-02 17:33:00 -0300
Maksim Kalmykov
  • 1,293
  • 3
  • 20
  • 26
martincito
  • 389
  • 4
  • 10
  • See also https://stackoverflow.com/questions/9727898/parsing-string-dates-in-ruby-such-as-28-may-10/9728030#9728030 or https://stackoverflow.com/questions/14511141/string-to-date-in-ruby/14511436#14511436. Your code would be `DateTime.strptime('20170802173300','%Y%m%d%H%M%S').strftime('%Y-%m-%d %H:%M:%S')` – knut Aug 02 '17 at 20:58

4 Answers4

3

You can use strftime:

datetime = 'Mie, 02 Ago 2017 17:33:00 -0300'
datetime.strftime('%Y-%m-%d %H:%m:%S %z')
# => 2017-08-02 17:33:00
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
2

You can format time anyway you like, in Ruby with strftime.

For format you want it'll be like this:

%Y-%m-%d %H:%M:%S %z

For example: Time.now.strftime('%Y-%m-%d %H:%M:%S %z')

Nikita Misharin
  • 1,961
  • 1
  • 11
  • 20
1
require 'date'
date = '20170802173300'
formatted_date = DateTime.parse(date).to_s
# => "2017-08-02T17:33:00+00:00"

# and to be more explicit:
really_formated_date = DateTime.parse(date).strftime('%Y-%m-%d %H:%M:%S %Z')
# => "2017-08-02 17:33:00 +00:00"
whodini9
  • 1,434
  • 13
  • 18
-1

Date now = new Date(); SimpleDateFormat format = new SimpleDateFormat("dd-MM-yy");