问题
I have a date in format "YYYYMMDDHH" and I want to add or subtract hours from it. The GNU date (date -d option) works like a charm in Linux but cant do this in non-GNU env like Solaris. Can someone please help me in how I can do this?
回答1:
You should check if gdate
is not already installed under your release of Solaris (might be in /usr/gnu/bin/date
, /usr/sfw/bin/[g]date
, /usr/local/bin/[g]date
, /usr/csw/bin/[g]date
or just /usr/bin/gdate
depending on the version). If not, it should be easy to find a package containing GNU date and install it.
Anyway, here is a shell function that should just work under a stock Solaris release and that do what I believe you want:
f()
{
echo $1 | perl -MTime::Local -nle '
use POSIX 'strftime';
$op='$2'*3600;
$sec=timelocal(0,0,$4,$3,$2-1,$1) if /(\d{4})(\d{2})(\d{2})(\d{2})/;
$sec=$sec+$op;
print strftime "%Y%m%d%H\n", localtime($sec);'
}
$ f 2014010112 -24
2013123112
回答2:
Just so that in case anyone lands here looking for answer to above "non-GNU date" question: following question is more appropriate with good answers: Date computations without GNU tools
来源:https://stackoverflow.com/questions/23503892/yyyymmddhh-date-manipulation-in-shell-script-in-unix