Linux 从日期获取月和日

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14490590/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:46:55  来源:igfitidea点击:

Get Month & Day from Date

linuxunixdate

提问by user1570210

I am trying to get Month and Date from Date in Linux. this is my code

我正在尝试从 Linux 中的日期获取月份和日期。这是我的代码

# Set Date 
D="2013/01/17"

# get day 
DD=$(D+"%d")

# get day 
MM=$(D+"%M")

# Day 
echo "Day:"$DD
echo "Month:"$MM

采纳答案by cyfur01

In shor bash:

shbash

D="2013/01/17"
DAY=$(date -d "$D" '+%d')
MONTH=$(date -d "$D" '+%m')
YEAR=$(date -d "$D" '+%Y')

echo "Day: $DAY"
echo "Month: $MONTH"
echo "Year: $YEAR"

回答by Kent

kent$  D="2013/01/17"

kent$  awk -F/ '{print "year:","Month:","Day:"}'<<<$D
year:2013 Month:01 Day:17

if you want just Month or Day, just leave $2 or $3 there, delete the parts you don't need

如果你只想要月或日,只需在那里留下 2 美元或 3 美元,删除不需要的部分

Edit

编辑

kent$  year=$(awk -F/ '{print }' <<<$D)                                                                                                                                   

kent$  echo $year
2013

回答by Anders Johansson

Or if you want the current date, use date +%Y/%m/%d. If you want them separately you can do something like this:

或者,如果您想要当前日期,请使用date +%Y/%m/%d. 如果你想要它们分开,你可以做这样的事情:

read YYYY MM DD <<<$(date +'%Y %m %d')
echo "Today is Day:$DD Month:$MM"

An easier approach is:

一个更简单的方法是:

DD=$(date +%d)
MM=$(date +%m)
echo "Today is Day:$DD Month:$MM"

However in this case you're executing datetwice, which is inefficient, and if you're really unlucky, the date could change between those two lines ;)

但是,在这种情况下,您执行了date两次,这是低效的,如果您真的不走运,这两行之间的日期可能会改变;)