12 hour to 24 hour time converter
MATL, 4 bytes
15XO
Try it online!
Explanation
Built-in function: date string conversion with automatic detection of input format and with output format 15
, which corresponds to 'HH:MM'
. This is equivalent to @StewieGriffin's Octave answer.
Octave, 21 17 bytes
Saved 4 bytes thanks to Luis Mendo. I could specify format number 15 instead of 'HHMM'
.
@(c)datestr(c,15)
Explanation:
This is an anonymous function taking a string c
as input on the format: '11:34 AM'
. datestr
recognizes the format automatically as one of the standard date formats, and outputs it in the specified format number 15, which is HH:MM
.
Since the specified output format doesn't have AM
or PM
Octave automatically converts it to what you refer to as Military time.
Try it online.
A version not using datestr
using 35 bytes
@(c)[c(1:4)+[1,2,0,0]*(c(5)>97),'']
Explanation:
Takes an input string c
on the format 1134am
.
@(c) % Anonymous function
[c(1:4) % First 4 elements of the string
+[1,2,0,0] % Add 1 and 2 to the first to the ASCII-value of the
first two characters
*)c(5)>97) % if the fifth element is larger than 97
(the ASCII code for `a`).
,''] % Implicitly convert to string
Or, a different approach for 37 bytes:
@(c)[c(1:4)+('1200'-48)*(c(5)>97),'']
V, 21 17 bytes
Thanks @DJMcMayhem for 4 bytes!
í12:/0:
çp/12
$x
Try it online!
This takes the format HH:MMx
where x
is either a
or p
, and returns it in the format HH:MM
Hexdump:
00000000: ed31 323a 2f30 3a0a e770 2f31 3201 2478 .12:/0:..p/12.$x
00000010: 0ae7 612f 2478 ..a/$x
Explanation:
í12:/0: | find and replace 12: with 0: (to avoid replacing HH:12)
ç | on every line
p/ | that contains a p
12^A | increment 12 times (the first number, hours)
$x | delete the character at the end of the line