1

Using date, I can convert days of weeks to integers ranging from 1 to 7, for example:

$ date -d "Thursday" +%u
4

But what if I want to perform the reverse operation? Something like,

$ date [options] [+format]
Thursday

It's okay if it's not possible with date, I can use other programs as well. Aiming for brevity here.

0

3 Answers 3

5

You could get the date for next Sunday, add N days and print the day name for that particular date:

getdayname () {
nextplus=$(date -d "next Sunday +$1 days")
date -d "${nextplus}" '+%A'
}

and run getdayname 2, getdayname 7 etc (assuming gnu date).
Or simply use an array and do without the date e.g.

getdayname () {
local days=( Sunday Monday Tuesday Wednesday Thursday Friday Saturday )
printf %s\\n ${days[$1]}
}

though with bash/ksh you need printf %s\\n "${days[$1-1]}" (as indexing starts at 0), and quotes are needed to avoid split+glob (also with yash).

2

Based on don_crissti's answer, since his first answer gives me incorrect results:

getdayname() {
        date -d "$(( 7-$(date '+%u')+$1 )) days" '+%A'
}
2

POSIXly (-d is not a standard date option. When available, it means something different to different implementations), to give the day name in the user's locale, Sunday being either 0 or 7:

getdayname() (
  IFS=';'
  set -o noglob
  days=$(locale day) || exit
  for day do
    set -- $days $days
    shift "$day" &&
      printf '%s\n' "$1"
  done
)

Examples:

$ getdayname 0 4 7
Sunday
Thursday
Sunday
$ LANG=es_VE.UTF-8 getdayname 0 4 7
domingo
jueves
domingo

With GNU or busybox date (whose -d ... doesn't support relative dates), or ast-open date (whose -d ... supports relative dates but in a different way from GNU's date):

getdayname() (
  for day do
    date -ud "1970-01-$((day + 11))" +%A
  done
)

With zsh without external requirements:

$ zmodload zsh/langinfo
$ day=0
$ printf '%s\n' $langinfo[DAY_$((day+1))]
Sunday

Or:

$ zmodload zsh/datetime
$ day=0
$ TZ=UTC0 strftime %A $((86400 * (3+day)))
Sunday
1
  • Great solution by using function. I use it in simple gist to get crypto prices. price.sh Commented May 27, 2024 at 12:57

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.