Results 1 to 4 of 4

Thread: am-pm in string

  1. #1
    Join Date
    Aug 2013
    Beans
    26

    am-pm in string

    HI guys

    i have a variable in bash which conatins a string with the time in 24 hour format as follows

    11:00 - 13:10
    this is scraped from the web not piped from a linux command is there any way to easy add am pm to it ?

    11:00 AM - 13:10 PM
    any help would be greatly appreciated

  2. #2
    Join Date
    Jul 2007
    Location
    Poland
    Beans
    4,402
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: am-pm in string

    13pm? is that even a thing? am/pm relate to 12hr clock


    Code:
    $ h24to12() { local h m ampm=(am pm); IFS=: read h m <<< "$1"; echo $(( (h+23)%12+1 )):$m${ampm[h/12%2]}; }; 
    $ t='11:00 - 13:10'
    $ t1=${t%% -*}; t2=${t##*- }
    $ echo "$(h24to12 "$t1") - $(h24to12 "$t2")"
    11:00am - 1:10pm
    Last edited by Vaphell; June 6th, 2014 at 11:07 AM.
    if your question is answered, mark the thread as [SOLVED]. Thx.
    To post code or command output, use [code] tags.
    Check your bash script here // BashFAQ // BashPitfalls

  3. #3
    Join Date
    Jun 2007
    Location
    Maryland, US
    Beans
    6,240
    Distro
    Kubuntu

    Re: am-pm in string

    You may have to decompose the string "11:00 - 13:10" into 3 parts that are separated by white-space. Then reconstruct a new string with the the first token, followed by AM, then then the hyphen, and finally the last token with the trailing PM string.

    Code:
    time="11:00 - 13:00"
    
    tokens=( $time )
    
    echo ${tokens[0]} AM ${tokens[1]} ${tokens[2]} PM
    Btw, if you are dealing with 24-hour clock representation, isn't it superfluous to use the AM and PM designations?

  4. #4
    Join Date
    Jul 2005
    Location
    England
    Beans
    Hidden!

    Re: am-pm in string

    Add %p to the string in your variable, though I'm not sure what exactly you mean by "this is scraped from the web not piped from a linux command is there any way to easy add am pm to it ?" so if this is not a standard bash variable it may not work as you want.
    DISTRO: Xubuntu 14.04-64bit --- Code-tags --- Boot-Repair --- Grub2 wiki & Grub2 Basics --- RootSudo

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •