如何在solaris 8中获取上一年和上个月

如何在solaris 8中获取上一年和上个月

如何在solaris 8中获取上一年和上个月?

我尝试过以下命令,但没有一个是正确的:

date +'%m' -d 'last month'
date +'%Y' -d 'last year'

答案1

Solarisdate不支持-dGNU 等选项date

您可以使用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

或者如果您有ksh93

$ printf "%(%m)T\n" "last month"
05  
$ printf "%(%Y)T\n" "last year"
2013

更新

对于@glennjackman的评论,我找到了一个文档时间::件模块:

   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.

因为OP只想获取前一年和前一个月,所以我们可以设置$t[3] = 1来解决这个问题。

答案2

对 perl 想法的修正(一月份的解决方案有问题,是吗?)。

最后一个月是:

$ perl -MPOSIX=strftime -le '@t = localtime; @l = localtime (time - @t[3] * 86400); print strftime("%m", @l)'

答案3

Tcl 有一个非常好的日期和时间实现,如果你安装了它:

tclsh <<END
puts [clock format [clock scan "-1 month"] -format "%m"]
puts [clock format [clock scan "-1 year"] -format "%Y"]
END

相关内容