Coolguy
Coolguy

Reputation: 3

UNIX previous month and year with format YYYYMM

I need to assign a variable with the value in the format YYYYMM e.g for today run the previous month values should be generated as

Var1 = 201607

Is there any in build method available? Could you share the steps to generate this?

Upvotes: 0

Views: 5134

Answers (1)

fedorqui
fedorqui

Reputation: 289755

The trick in these cases is to subtract one month from the day 15 of the current month:

$ date --date="$(date +%Y-%m-15) - 1 month"
Fri Jul 15 00:00:00 CEST 2016

Then it is just a matter of using the proper format:

$ date --date="$(date +%Y-%m-15) - 1 month" "+%Y%m"
201607

To store the value in a var, just use the common var=$(command) syntax.

From GNU Coreutils → 28.7 Relative items in date strings:

The fuzz in units can cause problems with relative items. For example, ‘2003-07-31 -1 month’ might evaluate to 2003-07-01, because 2003-06-31 is an invalid date. To determine the previous month more reliably, you can ask for the month before the 15th of the current month. For example:

$ date -R
Thu, 31 Jul 2003 13:02:39 -0700
$ date --date='-1 month' +'Last month was %B?'
Last month was July?
$ date --date="$(date +%Y-%m-15) -1 month" +'Last month was %B!'
Last month was June!

Also, take care when manipulating dates around clock changes such as daylight saving leaps. In a few cases these have added or subtracted as much as 24 hours from the clock, so it is often wise to adopt universal time by setting the TZ environment variable to ‘UTC0’ before embarking on calendrical calculations.

Upvotes: 3

Related Questions