Manipulate date in UNIX

大憨熊 提交于 2019-12-02 08:48:04

问题


I want to find a way to list all the dates of the current week in UNIX. For example if today is 17-07-2018 then how to get dates 16-07, 18-07, 19-07 and so on for the whole week? I.e., yesterday, tomorrow, day after tomorrow etc. I cannot use --date/d options with date command as GNU is not installed. Any other commands or a user defined function to get all the dates of the given (current or any date)?


回答1:


Assuming your date recognizes TZ offsets in hours, this works for the current date:

#!/bin/sh

case $(date +%A) in
  (Monday)    off="  +0  -24 -48 -72 -96 -120 -144";;
  (Tuesday)   off=" +24   +0 -24 -48 -72  -96 -120";;
  (Wednesday) off=" +48  +24  +0 -24 -48  -72  -96";;
  (Thursday)  off=" +72  +48 +24  +0 -24  -48  -72";;
  (Friday)    off=" +96  +72 +48 +24  +0  -24  -48";;
  (Saturday)  off="+120  +96 +72 +48 +24   +0  -24";;
  (Sunday)    off="+144 +120 +96 +72 +48  +24   +0";;
esac
for o in $off; do
   TZ="$o" date +%d-%m
done

Sample run:

$ date
Sun Jul 15 23:13:43 CEST 2018
$ ./x.sh
09-07
10-07
11-07
12-07
13-07
14-07
15-07

This has no problem with leap years, under/overflow, since it uses date's built-in knowledge.

PS: I just discovered that my date (on FreeBSD) takes these offsets from UTC, not the systems time zone; you should investigate this for AIX and if so, adjust the offsets accordingly by your local time zone offset to UTC.




回答2:


Well, now I think it requires GNU!date or some actual programming language. Perl, for instance.

#!/usr/bin/perl

use strict;
use POSIX;

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
my ($w,$ts);

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime();

$ENV{'TZ'}='GMT';
POSIX::tzset ();

$ts = POSIX::mktime (0, 0, 0, $mday, $mon, $year);
$ts = $ts - 24*60*60 * $wday;

for ($w= 1; $w<=7; ++$w) {
    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
        gmtime($ts + (24*60*60)*$w);
    printf ("%04d-%02d-%02dn", $year+1900, $mon+1, $mday);
}

If you save it as $HOME/bin/weekdays.pl then you can use it in your scripts:

set $(perl ~/bin/weekdays.pl)
echo "Monday is $1"


来源:https://stackoverflow.com/questions/51351699/manipulate-date-in-unix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!