junkone
junkone

Reputation: 1465

Change date-format in Ruby?

I am using Rails and trying to import a logfile. The date-format that the log has is yyyymmdd;hhmmss:

20121216;233550

My MySQL server uses this to for its insert statements:

 MM/DD/YYYY HH:MM:SS 

How can I convert this string-format to the date-format?

Upvotes: 0

Views: 1647

Answers (3)

iced
iced

Reputation: 1572

require 'date'
DateTime.strptime('20121216;233550', '%Y%m%d;%H%M%S').strftime('%m/%d/%Y %H:%M:%S')

No magic, really.

Upvotes: 3

mesozoic
mesozoic

Reputation: 700

If you're using Rails (which loads ActiveSupport), that format appears parseable using Time#parse:

Time.parse(source_dt).strftime('%m/%d/%Y %H:%M:%S')

Upvotes: 0

DGM
DGM

Reputation: 26979

Assuming that format remains fixed and contains no errors, you can create a Time object with:

d="20121216;233550"
Time.mktime(d[0..3], d[4..5],d[6..7],d[9..10],d[11.12],d[13..14])

Upvotes: 0

Related Questions