How to obtain a day of the week from the date?

I have a date in format YYYYMMDD, i need to get the day of the week from the given date. I am working in AIX system.

---------- Post updated at 09:59 AM ---------- Previous update was at 09:57 AM ----------

Tried to post sum of the thread's link from which i tried, but de rules didnt allow me to post them!!!

#!/bin/ksh

DATE="yyyymmdd"

echo "${DATE:6:2}"

This is one way in bash shell:

date -d2012-11-28 +'%A %u'

spacebar, this is not a 'bash feature'. date is an external utility, not part of bash -- your code would work equally well in a variety of shells, but has one problem. The -d switch is a nonstandard GNU feature, something vanilla AIX does not have.

Running the date external utility to extract two characters from a string is overkill of the nth order, in any case.

perl -MPOSIX=mktime -e '@wday=qw(Sun Mon Tue Wed Thu Fri Sat);
$ARGV[0] =~ /(....)(..)(..)/;
print $wday[(localtime mktime(0,0,0,$3,$2-1,$1-1900))[6]],"\n"' YYYYMMDD

Replace YYYYMMDD with your date.

Hi elixir... can u pls explain the solution?

---------- Post updated at 11:14 AM ---------- Previous update was at 11:10 AM ----------

Hi spacebar... Theres s no -d option available in AIX flavour

That's using the mktime subroutine from the POSIX core perl module (check perldoc POSIX for more details) to convert the given time to seconds since the Epoch. Then, the localtime builtin function (see perldoc perlfunc for the details) is used to convert that value to a list. In this list, the 7th value (index 6) is the weekday. Then, this weekday value is used as an index to get the required weekday name from the defined list.

Did you search our forums?
e.g.

Is only the latest... e.g

there are quite a few more to look at not mentionning:
http://www.unix.com/answers-frequently-asked-questions/13785-yesterdays-date-date-arithmetic.html

1 Like

Hi corona, U r code is throwing bad substitution error.

"${DATE:6:2}": bad substitution

You need ksh93/bash for that...