10

From a given date in %m-%d-%Y format we should determine what day it is.

Example: for the date 09-01-2017 output should be Friday

thanasisp
  • 5,855
  • 3
  • 14
  • 31
Divya S
  • 141
  • 1
  • 2
  • 5
  • 1
    Related (getting a numerical output instead of a word for weekday): https://stackoverflow.com/questions/22956516/getting-day-of-week-in-bash-script – Pluto Nov 04 '19 at 17:57

6 Answers6

6

Very simple. Just use the date command itself with correct options.

$ date -j -f '%m-%d-%Y' "09-01-2017" +'%A'
Friday
nagendra547
  • 5,672
  • 3
  • 29
  • 43
  • 4
    Since this is neither GNU `date` or BSD `date` you may want to specify what `date` it is. I'm guessing macOS? – Kusalananda Sep 03 '17 at 15:34
4

If you have your date like this:

d="09-01-2017"

you need to reformat it to "YYYY-MM-DD"

date -d $(echo $d|awk -F- '{print $3 "-" $1 "-" $2}') +%A # DOW 
4

Here is what I usually do. I would use the date function. you can do 'man date' and find options.

$ d=2020-08-20 \
$ date -d "$d" +%u \
4 \
$ date -d "$d" +%A \
Thursday
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
S Asi
  • 43
  • 5
3
DayOfWeek=$(date +%A)

This would yield the day of week monday-sunday If your input date is strictly in the format MM-DD-YYYY, use the following

IFS='-' read -ra ADDR <<< "09-01-2017"
formattedDate=${ADDR[2]}-${ADDR[0]}-${ADDR[1]}
date -d  $formattedDate +%A

The first line tokenizes the components of the date and the second rearranges them

Rajeev Ranjan
  • 3,588
  • 6
  • 28
  • 52
1

You can pass it as %m/%d%Y which gets recognized by the date command.

$ date --date="`echo 09-01-2017| sed -e 's/-/\//g' `" +'%A'
Friday

To verify it, pass %F to get it in ISO format

$ date --date="`echo 09-01-2017| sed -e 's/-/\//g' `" +'%A %F'
Friday 2017-09-01
stack0114106
  • 8,534
  • 3
  • 13
  • 38
-1
date +%A
# let us see in a for loop
for i in {1..7}; do date +%A --date=+${i}day; done

Wednesday
Thursday
Friday
Saturday
Sunday
Monday
Tuesday
stefansson
  • 457
  • 4
  • 5