Writing a shell script to display time in am or pm

I am trying to write a shell script that displays time in am or pm, and not as shown with the date command. I'm not sure how I should do this. I think, for starters, how do I extract time from the date command to manipulate it? And how can I extract the number in an hour to manipulate it?

+7
source share
5 answers

What you are looking for is

man strftime 

This means that the format string-format-time is used, which is used in the date format.

So, to get the current AM / PM, use the following:

 date +"%p" 

or

 ampm=`date +"%p"` echo $ampm 

An hour can be one of several formats (do you want a 12 or 24 hour time, zero or not?) I assume you want a 12 hour time without a leading zero:

 date +"%l" 
+7
source

not as shown with the date command

The date command accepts a format string. On delivery, %p will display either "AM" or "PM" according to the specified time value or the corresponding lines for the current locale. Noon is regarded as β€œPM” and midnight as β€œAM”:

 % date +'%H:%M %p' 08:01 am 

β€œUnder the hood,” this calls strftime() . For more information on formatting, see the Man page.

+2
source

You can use below units to print time in AM and PM format up to minutes.

 echo $(date +"%I:%M %p") 

OutPut : 21:20

or

 echo $(date +"%r") 

Output : 09:20:09 PM

or echo $ (date + "% I% p")

Output : 09 PM

+2
source

You can use the "+" formatting option of the date command. For example:.

  > date +%l%p -> 7PM 
+1
source

It depends on the locale settings.

 LC_TIME="C" date +%l%p LC_TIME="C" date +'%l:%M %p' 
+1
source

All Articles