16

I want the UNIX date to output:

So this is week 35 of 2016.

Here, of course, 35 and 2016 are outputs of the date command. I have tried the following:

date +%U

This printed out the current week number. But I have to wrap it inside the specific text I want to display. I tried:

date "So this is week: %U"
date "It is currently: "+ "%U"

Both gave me an error. How can I make the date command display the week number to me in the specific format that I desire?

5 Answers 5

25

The entire format string is to be preceded by the +:

$ date +"So this is week: %U"
So this is week: 19
$ date +"So this is week: %U of %Y"
So this is week: 19 of 2016
2
  • Thank you. How to add the 'year' after the week '19' part though? e.g. So this is week 35 of 2016.
    – learnerX
    May 11, 2016 at 20:20
  • 1
    Add a of %Y after the %U in the string.
    – muru
    May 11, 2016 at 20:21
11

There are two kinds of week:

  • Monday as first day
  • Sunday as first day

So its not all the same when you are in different day of a week(CentOS7):

[[email protected]:~]# date
Mon Aug 26 18:02:47 CST 2019

[[email protected]:~]# date +%U
34

[[email protected]:~]# date +%V
35
date --help
  %U   week number of year, with Sunday as first day of week (00..53)  
  %V   ISO week number, with Monday as first day of week (01..53)
8

There are actually 3 kind of week number in year for the date command :

  • %U week number of year, with Sunday as first day of week (00..53)
  • %W week number of year, with Monday as first day of week (00..53)
  • %V ISO week number, with Monday as first day of week (01..53)
2

I'd like to add the command substitution using backquotes (``) like this:

echo "So this is week `date +%V` of `date +%Y`."

They are evaluated before the expression is processed further and often come in handy, if a command doesn't provide that feature. Nevertheless - since date is capable of it, murus' answer seems to be best practice in that case.

1

don't mess calendar week/year with ISO week/ISO year! e.g. the solution

echo "So this is week `date +%V` of `date +%Y`."

is not correct!, because for example for 1.1.2023 it will return nonsence:

> date -d "2023/01/01" +"%F is week %V year %Y"
2023-01-01 is week 52 year 2023

only use pairs +%V +%G for ISO calendar, or +%W/%U +%Y for normal calendar:

> date -d "2023/01/01" +"%F is week %V year %G"
2023-01-01 is week 52 year 2022
> date -d "2023/01/01" +"%F is week %W year %Y"
2023-01-01 is week 00 year 2023

more info on Wiki: ISO week date

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .