Write a program called thetime that displays the time of day in am or pm notation rather than in 24-hour clock time.
$ date
Wed Aug 28 19:34:01 EDT 2002
$ thetime
7:21 pm
Suggestion: Use the shell's built-in integer arithmetic to convert from 24-hour clock time. Then rewrite the program to use a case command instead. Rewrite it again to perform arithmetic with the expr command.
There are two ways to solve this. The date command has a rich formatting language that students can learn about by typing man strftime, which yields this delightful one-line command:
date +"%l:%M %p"
Failing that, the suggested solution produces a complex script:
hour=$(date | cut -d\ -f5 | cut -d: -f1)
min=$(date | cut -d\ -f5 | cut -d: -f2)
case $hour in
0[1-9]|[1-9]|10|11|12 ) echo "${hour}:$min am"
;;
0 ) echo "12:$min pm"
;;
* ) echo "$(( $hour - 12)):$min pm"
;;
esac
It's worth noting is that the date command reports hours in a 0-23 format, not 1-24, so midnight is not hour 24 on its 24 hour clock, but hour zero. That's why you need the special case for that situation so you don't get "-12:05 pm" as a late-night output.
You might also like to view...
To prevent a report from printing blank pages, the user should remove extra space from the report
Indicate whether the statement is true or false
The program that enables another program to run within Internet Explorer is called a(n):
A) script B) ActiveX control C) keystroke logger D) patch
When creating a link, including a space in the filename will result in a broken link
Indicate whether the statement is true or false
Whistle-blowers
a. make an unauthorized discloser about a harmful situation or fraud. b. usually gain the respect and admiration of their colleagues. c. are usually financially rewarded by their organizations for their integrity. d. typically get promoted to management. e. All of the above