2

I have a bunch of time based strings saved per object in my db that are formatted like this:

"01:00 PM"

Doing a little bit of research I came across a post that shows you how to convert a string similar to but not exactly how mine is. The difference being the example has no colon in between the hour and minute integers, which throws a snag in the answer's conversion:

Time.strptime("1:00 PM", "%I%P").strftime("%H:%M")
# ArgumentError (invalid strptime format - `%I%P')

Is there still a way to get this conversion to work given my particular format?

Carl Edwards
  • 13,826
  • 11
  • 57
  • 119
  • Converting `12:00 PM` to `12:00` might not be the best example. – Stefan Jan 06 '20 at 13:13
  • Not sure what you mean. – Carl Edwards Jan 06 '20 at 13:14
  • `12` exists in both, the 12-hour and the 24-hour clock. It would be more obvious to pick an example like `01:00 PM` → `13:00` or `11:00 PM` → `23:00`. – Stefan Jan 06 '20 at 13:18
  • Oh okay I gotchu. Thanks for pointing this out. I’ll update in a few. – Carl Edwards Jan 06 '20 at 13:21
  • Just a note that you don't have to use `Time` methods (but it's simpler if you do): `if str.end_with?('AM'); str.sub(/ PM/,''); else; hr, min = str.scan(/\d+/).map(&:to_i); "%d:%02d" % (60*hr + min + 12*60).divmod(60); end`. If, for example, `str = "1:07 PM"`, this returns `"13:07"`. – Cary Swoveland Jan 06 '20 at 18:23

2 Answers2

3

Have you tried this? time = "12:00 PM"

Time.strptime(time, "%I:%M %P").strftime("%H:%M")

Roman Alekseiev
  • 1,854
  • 16
  • 24
  • With this I get the error: `ArgumentError (invalid strptime format - '%I%M%P')` – Carl Edwards Jan 06 '20 at 12:37
  • do you use exact `"%I:%M %P"` as second argument? there is semicolon and space between `%M` and `%P` – Roman Alekseiev Jan 06 '20 at 12:42
  • I also recommend checking this doc: https://apidock.com/ruby/DateTime/strftime it has full set of options for `strftime`. Differences between strftime and strptime are here https://stackoverflow.com/questions/14619494/how-to-understand-strptime-vs-strftime (pretty same, in short) – Xentatt Jan 06 '20 at 13:24
0

You have to pass the format of time in strptime method so you have to pass '%I:%M %P' and if you don't want semicolon in time than you have to pass the values according to it in strftime method as '%H%M' so you'll get your answer as you requirement.

Time.strptime('10:00 PM', '%I:%M %P').strftime("%H%M") this will give you output "2200" and

Time.strptime('10:00 PM', '%I:%M %P').strftime("%H:%M") this will give you output "22:00".

Thank You.