Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Month & Day from Date

Tags:

date

linux

unix

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

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

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

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

# Day 
echo "Day:"$DD
echo "Month:"$MM
like image 271
user1570210 Avatar asked Jan 23 '13 22:01

user1570210


People also ask

What does getMonth return?

The getMonth() method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).

What is new date () in JavaScript?

It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.


3 Answers

In sh or bash:

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" 
like image 80
cyfur01 Avatar answered Sep 29 '22 17:09

cyfur01


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

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 date twice, which is inefficient, and if you're really unlucky, the date could change between those two lines ;)

like image 44
Anders Johansson Avatar answered Sep 29 '22 18:09

Anders Johansson


kent$  D="2013/01/17"

kent$  awk -F/ '{print "year:"$1,"Month:"$2,"Day:"$3}'<<<$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

Edit

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

kent$  echo $year
2013
like image 27
Kent Avatar answered Sep 29 '22 18:09

Kent