Question

I have datetime strings that are outputted in the following format:

03/27/2014 07:52:47 PM

I'm using a gem called rufus-scheduler, which takes strings in a YYYY-mm-dd hh-MM-ss #### (#### is timezone offset). Are there any easy ways to convert the first string I had to a string in the format rufus-scheduler likes?

I know that one way I could do it would be to create a method that parsed the string so I could create a new datetime object from it, and then call a strftime in the format rufus likes, but I was wondering if there were any more efficient ways to go about solving my problem.

Was it helpful?

Solution

You can use DateTime::strptime to parse, and DateTime#strftime to format it again.

First require 'date' and then:

2.0.0-p451 :021 > DateTime.strptime("03/27/2014 07:52:47 PM", "%m/%d/%Y %H:%M:%S %p").strftime("%Y-%m-%d %H-%M-%S %z")
 => "2014-03-27 19-52-47 +0000"

OTHER TIPS

Check out Time.strftime

Also, http://www.foragoodstrftime.com/ is an awesome tool for this.

Chronic (https://github.com/mojombo/chronic) is your friend

require 'chronic'

p Chronic.parse('03/27/2014 07:52:47 PM')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top