How to get previous year and previous month in solaris 8
14,735
Solution 1
Solaris date
does not support -d
option like GNU date
.
You can use perl
:
$ perl -MPOSIX=strftime -le '@t = localtime; $t[3] = 1; $t[4]--; print strftime("%m", @t)'
05
$ perl -MPOSIX=strftime -le '@t = localtime; $t[3] = 1; $t[5]--; print strftime("%Y", @t)'
2013
Or if you have ksh93
:
$ printf "%(%m)T\n" "last month"
05
$ printf "%(%Y)T\n" "last year"
2013
Updated
For @glennjackman's comment, I found a documentation in Time::Piece module:
The months and years can be negative for subtractions. Note that there is some "strange" behaviour when adding and subtracting months
at the ends of months. Generally when the resulting month is shorter than the starting month then the number of overlap days is
added. For example subtracting a month from 2008-03-31 will not result in 2008-02-31 as this is an impossible date. Instead you will
get 2008-03-02. This appears to be consistent with other date manipulation tools.
Because the OP only want to get previous year and month, we can set $t[3] = 1
to fix this problem.
Solution 2
A corrective to the perl idea (There is a problem with that solution in the month of January, yes?).
The last month is:
$ perl -MPOSIX=strftime -le '@t = localtime; @l = localtime (time - @t[3] * 86400); print strftime("%m", @l)'
Related videos on Youtube
Author by
Kumar1
Updated on September 18, 2022Comments
-
Kumar1 almost 2 years
How to get previous year and previous month in solaris 8?
I have tried below command but none of them is correct:
date +'%m' -d 'last month' date +'%Y' -d 'last year'
-
cuonglm about 10 yearsWhat command did you use?
-
Kumar1 about 10 years
date +'%m' -d 'last month'
date +'%Y' -d 'last year' -
jw013 about 10 yearsAs far as I know only the GNU version of
date
has a-d
option that accepts input likelast month
orlast year
. -
lornix about 10 years
expr $(date +%m) - 1
andexpr $(date +%Y) - 1
work well too. -
Kumar1 about 10 yearsThanks @lornix , for previous year "expr $(date +%Y) - 1" command works for me . but for month am expecting result in standard numerical format like 05,06,07...any suggestion ?
-
lornix about 10 yearsThe leading zero is going to cause issues with 08 & 09 (octal value implied by leading zero)... but ok....
printf "%02d" $(expr $(date +%-m) - 1)
should produce the output you're looking for. (The %-m tells date to not pad with zeros, avoiding the octal problem during the printf operation)
-
-
Angel Todorov about 10 years+1 for the perl suggestion. It's not foolproof though, March 30 minus one month will give you March 2 (Feb 30 is assumed to be Feb 28 plus 2 days, in a non-leap year). Date arithmetic can be odd.
-
cuonglm about 10 years@glennjackman: I updated my answer to work around this problem, just set the date to 1.