bash 编写 shell 脚本以使用 am 或 pm 表示法显示时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15056591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing shells script to display time in am or pm notation
提问by zyxxwyz
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?
我正在尝试编写一个 shell 脚本,以 am 或 pm 显示时间,而不是使用 date 命令显示的方式。我不知道我应该如何去做这件事。我想对于初学者来说,如何从 date 命令中提取时间来操作它?以及如何提取小时数来操作它?
回答by valbaca
What you're looking for is
你要找的是
man strftime
That stands for string-format-time, which is the format that date
uses.
这代表字符串格式时间,这是date
使用的格式。
So to get the current AM/PM, use the following:
因此,要获取当前的 AM/PM,请使用以下命令:
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:
小时可以是多种格式之一(您想要 12 小时还是 24 小时时间,前导零与否?)我猜您想要非前导零 12 小时时间:
date +"%l"
回答by Venkat
You can use below one to print time in AM and PM format up to minutes.
您可以使用下面的一个以 AM 和 PM 格式打印时间,最长可达分钟。
echo $(date +"%I:%M %p")
OutPut: 09:20 PM
输出: 09:20 PM
or
或者
echo $(date +"%r")
Output: 09:20:09 PM
输出: 09:20:09 PM
or echo $(date +"%I %p")
或 echo $(date +"%I %p")
Output: 09 PM
输出: 09 PM
回答by Johnsyweb
rather than the way it is shown using date command
而不是使用 date 命令显示的方式
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
命令采用格式字符串。Supplying%p
将根据给定的时间值或当前语言环境的相应字符串显示“AM”或“PM” 。中午被视为“PM”,午夜被视为“AM”:
% date +'%H:%M %p'
08:01 am
"Under the hood", this calls strftime()
. See the man-page for more formatting options.
“在引擎盖下”,这称为strftime()
. 有关更多格式选项,请参阅手册页。
回答by shrike
It's depends on locale settings.
这取决于区域设置。
LC_TIME="C" date +%l%p
LC_TIME="C" date +'%l:%M %p'
回答by user12524232
To get AM or PM as am or pm try this date +%#p
要将 AM 或 PM 设为 am 或 pm 试试这个日期 +%#p
回答by shx2
You can use the "+" formatting option of the date command. E.g.:
您可以使用日期命令的“+”格式选项。例如:
> date +%l%p
-> 7PM
回答by Swathi Antony
Use date +"%P" capital P to display am or pm
使用日期 +"%P" 大写 P 来显示 am 或 pm