Solaris 10无date -d选项时,实现Unix时间加减n天的方法求助
Since you can't use the -d flag with Solaris 10's date (even /usr/xpg4/bin/date) and can't install any extra Perl modules or tools, here are two reliable, pre-installed-only methods:
Method 1: Use Perl with Core Modules
Solaris 10's pre-installed Perl includes Time::Local (a core, always-present module), which we can leverage to handle date arithmetic without extra dependencies.
Example 1: Add/Subtract days to the current date
Run these one-liners directly in your shell:
# Add 5 days to today perl -MTime::Local -e '@t = localtime(time + 5*86400); printf "%04d-%02d-%02d\n", $t[5]+1900, $t[4]+1, $t[3]' # Subtract 3 days from today perl -MTime::Local -e '@t = localtime(time - 3*86400); printf "%04d-%02d-%02d\n", $t[5]+1900, $t[4]+1, $t[3]'
Example 2: Add/Subtract days to a specific date (format: YYYY-MM-DD)
Save this as a reusable script (name it date_adjust.pl):
#!/usr/bin/perl use Time::Local; die "Usage: $0 <YYYY-MM-DD> <days_to_add_or_subtract>" unless @ARGV == 2; my ($date_str, $days) = @ARGV; my ($year, $mon, $mday) = split /-/, $date_str; # Convert target date to epoch (note: months are 0-based in Time::Local) my $epoch = timelocal(0, 0, 12, $mday, $mon-1, $year-1900); # Calculate new epoch by adding/subtracting days (1 day = 86400 seconds) my $new_epoch = $epoch + $days * 86400; # Convert back to human-readable date my ($sec, $min, $hour, $new_mday, $new_mon, $new_year) = localtime($new_epoch); printf "%04d-%02d-%02d\n", $new_year+1900, $new_mon+1, $new_mday;
Make it executable with chmod +x date_adjust.pl, then use it like so:
# Add 10 days to 2024-05-15 ./date_adjust.pl 2024-05-15 10 # Subtract 7 days from 2024-05-15 ./date_adjust.pl 2024-05-15 -7
Method 2: Use /usr/xpg4/bin/date with Epoch Arithmetic
Solaris 10's XPG4 date supports the %s format to output epoch time (seconds since 1970-01-01). We can calculate the epoch for our target date and convert it back to a readable format.
Example 1: Add/Subtract days to today
# Add 5 days to today new_epoch=$(( $(/usr/xpg4/bin/date +%s) + 5*86400 )) /usr/xpg4/bin/date -r $new_epoch +"%Y-%m-%d" # Subtract 3 days from today new_epoch=$(( $(/usr/xpg4/bin/date +%s) - 3*86400 )) /usr/xpg4/bin/date -r $new_epoch +"%Y-%m-%d"
Example 2: Add/Subtract days to a specific date
To handle a custom input date, combine the epoch approach with the Perl core module trick to convert the input date to epoch first:
# Example: Add 7 days to 2024-05-15 input_date="2024-05-15" days=7 # Convert input date to epoch using Perl's core Time::Local epoch=$(perl -MTime::Local -e '($y,$m,$d)=split/-/,shift;print timelocal(0,0,12,$d,$m-1,$y-1900)' "$input_date") new_epoch=$(( epoch + days*86400 )) /usr/xpg4/bin/date -r $new_epoch +"%Y-%m-%d"
Both methods stick strictly to pre-installed tools and avoid any external dependencies, so they’ll work within your system’s strict constraints.
内容的提问来源于stack exchange,提问作者JimR

