Ruby date time in string conversion to date time with milliseconds

ruby

Solution

This can be done very easily using the Time class. You can add to a Time by adding seconds. Then use #strftime

t= Time.parse('29 Sep 2013 12:25:00.367')
=> 2013-09-29 12:25:00 -0400
t=t + 10
=> 2013-09-29 12:25:10 -0400
t.strftime("%d %b %Y %H:%M:%S.%3N")
=> "29 Sep 2013 12:25:10.367"

Problem

This is a Ruby question (1.9.1) I have the following date and time in a string: ``` 29 Sep 2013 12:25:00.367 ``` I first want to convert it from string to date and time and then add 10 seconds to it and convert it back to the same string format as above. I wrote this code: ``` format = "%d %b %Y %H:%M:%S" date_time = "29 Sep 2013 22:11:30.195" parsed_time = DateTime.strptime(date_time, format) puts " new date time is #{parsed_time}" ``` Which outputs: ``` new date time is 2013-09-29T22:11:30+00:00 ``` I did not see "195". I tried `format = "%d %b %Y %H:%M:%S.%3N"` and this gives: ``` fileOpTest:34:in `strptime': invalid date (ArgumentError) from fileOpTest:34:in `<main>' ```

Original source