I'm trying to write a shell script that displays the time in am or pm rather than the way it is shown using date command. I'm not sure how I should go about doing this. I guess for starters, how do I extract the time from the date command to manipulate it? And how do I extract the number for the hour to manipulate it?
What you're looking for is
man strftime
That stands for string-format-time, which is the format that date
uses.
So to get the current AM/PM, use the following:
date +"%p"
or
ampm=`date +"%p"`
echo $ampm
The hour can be one of several formats (do you want 12 or 24 hour time, leading zero or not?) I'm guessing you want non-leading-zero 12 hour time:
date +"%l"
You can use below one to print time in AM and PM format up to minutes.
echo $(date +"%I:%M %p")
OutPut: 09:20 PM
or
echo $(date +"%r")
Output: 09:20:09 PM
or echo $(date +"%I %p")
Output: 09 PM
rather than the way it is shown using date command
The date
command takes a format string. Supplying %p
will display either "AM" or "PM" according to the given time value, or the corresponding strings for the current locale. Noon is treated as "PM" and midnight as "AM":
% date +'%H:%M %p'
08:01 am
"Under the hood", this calls strftime()
. See the man-page for more formatting options.
It's depends on locale settings.
LC_TIME="C" date +%l%p
LC_TIME="C" date +'%l:%M %p'
You can use the "+" formatting option of the date command. E.g.:
> date +%l%p
-> 7PM
Use date +"%P" capital P to display am or pm