awojo
awojo

Reputation: 967

ruby parse date using strptime and strftime

So I'm parsing this string from AIX's errpt - to convert it into epoch - and it doesn't seem to be respecting the Hour and Minute part of the string.

So the string is: 1108095913 (MMDDHHMMYY) .. but when I do my strptime to convert it to a date object, and then format it how I want, it completely zero'd out my hour and minute.

Am I missing something?

irb(main):039:0> Date.strptime("1108095913", "%m%d%H%M%y").strftime('%m/%d/%y %H:%M')

=> "11/08/13 00:00"

Upvotes: 2

Views: 4221

Answers (2)

Paulo Bu
Paulo Bu

Reputation: 29804

Use DateTime instead of Date:

irb(main):002:0> require 'date'
=> true
irb(main):003:0> DateTime.strptime("1108095913", "%m%d%H%M%y").strftime('%m/%d/%y %H:%M')
=> "11/08/13 09:59"

The reason is DateTime handles date and time, both and Date only handles date.

Hope this helps!

Upvotes: 1

Bogdan Agafonov
Bogdan Agafonov

Reputation: 157

You should use Time.strptime instead of Date method, Date removes hours and minutes

1.9.3-p429 :005 > Time.strptime("1108095913", "%m%d%H%M%y").strftime('%m/%d/%y %H:%M')
 => "11/08/13 09:59"

Upvotes: 2

Related Questions