Home > database >  shell scripting bash 12hour to 24hour conversion
shell scripting bash 12hour to 24hour conversion

Time:04-18

I need to convert the time from 12-hour time to 24hr time And converts this to 24hr time Input 03:25PM Output 15:25

CodePudding user response:

Using perl:

$ LC_TIME=C perl -MTime::Piece -pe 's/\b\d\d:\d\d[AP]M\b/Time::Piece->strptime($&, q{%I:%M%p})->strftime(q{%H:%M})/eg' <<<"03:25PM and 05:15AM"
15:25 and 05:15

Uses the core Time::Piece module to parse and format input words that match two digits followed by a colon followed by two more digits and either AM or PM.

An alternative is something like

perl -pe 's/\b(\d\d:\d\d)AM\b/$1/g; s/\b(\d\d):(\d\d)PM\b/($1   12) . ":$2"/eg'

where one regular expression matches AM times and removes the AM, and one matches PM times and removes the PM while adding 12 to the hours component.

CodePudding user response:

Using date:

date -d '3:25pm'  '%H:%M'

Output: 15:25

As for finding all occurrences of time in that format:

grep -Ei '[0-9] :[0-9] [ap]m'
  • Related