Question

I have a script which calls an API. The API returns a dateTime.iso8601 object. I can't seem to figure out how to get the leading zero on the minutes, though.

I've looked at other questions here that say to use strftime, but that throws undefined method 'strftime'.

I've tried the following:

systems.each do |system|
    time = system["last_checkin"].strftime('%H:$M')
    print "#{system['name']} #{time}\n"
end

systems.each do |system|
    time = system["last_checkin"]
    hour = time.strftime('%H')
    min = time.strftime('%m')
    print "#{system['name']} #{hour}:#{min}\n"
end

And a few others that I no longer recall.

How should I be approaching this?

Was it helpful?

Solution

try

system["last_checkin"].to_time.strftime('%H:%M')

which will convert it to a Time(which has the date) and then you can use strftime to get the format you want

OTHER TIPS

After digging around and piecing together the snippets of information I have and have received I was finally able to find something that made sense to me.

I simply formatted the time.min string:

min = "%02d" % time.min

I also added 12 to time.hour to get the 24-hour format.

systems.each do |system|
    time = system["last_checkin"]
    hour = time.hour + 12
    min = "%02d" % time.min
    print "#{system['name']} #{hour}:#{min}\n"
end

I imagine there is a more concise way to do this, but being new to Ruby, I'm content with this.

EDIT: While writing up my solution jtzero posted the more concise way I was expecting would be possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top