I need to substract some date from current date to determine the age of some connections. The date is in this format: YYMMDDHHMISS
. The output can be pretty much anything that I can use to determine lets say oldest connection, number of connections older than 1 hour, 1 week, 1 month.
Example of input date: 211013134247
I got to the point of getting date in this format from date
command (date '+%g%m%d%H%M%S'
), but I don't know how to correctly substract this to get accurate result.
I tried this, but this get problematic as soon as one number from connection date (like seconds) is bigger than current date. Example: connection has 53 as seconds and current seconds are 47.
$line = connection date
$date = current date
year= $((${date:0:2} - ${line:0:2}))
month= $((${date:2:2} - ${line:2:2}))
day= $((${date:4:2} - ${line:4:2}))
hour= $((${date:6:2} - ${line:6:2}))
minute= $((${date:8:2} - ${line:8:2}))
second= $((${date:10:2} - ${line:10:2}))
age=$year$month$day$hour$minute$second
I also tried this (some code shamelessly stolen from stack exchange), but the output is wrong.. I would expect something like: 0607********
, as in 6 years 7 months etc.. Input dates generally should not be years apart, so year calculation could be left out.
date="211013150325"
line="150325113419"
convert_date(){ printf `date '+%C'`'%s-%s-%s %s:%s:%s' ${1:0:2} ${1:2:2} ${1:4:2} ${1:6:2} ${1:8:2} ${1:10:2}; }
diff_dates(){
TS1=$(date -d "$1" +%s)
TS2=$(date -d "$2" +%s)
TZ=UTC date -d @$((TS1-TS2)) +%g%m%d%H%M%S
#+%Y.%m.%d.%H:%M:%S
}
date_converted=`convert_date $date`
echo $date_converted
line_converted=`convert_date $line`
echo $line_converted
diff_dates $date_converted $line_converted
root@SomeHost:~# date="211013150325"
root@SomeHost:~# line="150325113419"
root@SomeHost:~# convert_date(){ printf `date '+%C'`'%s-%s-%s %s:%s:%s' ${1:0:2} ${1:2:2} ${1:4:2} ${1:6:2} ${1:8:2} ${1:10:2}; }
root@SomeHost:~# diff_dates(){
> TS1=$(date -d "$1" +%s)
> TS2=$(date -d "$2" +%s)
> TZ=UTC date -d @$((TS1-TS2)) +%g%m%d%H%M%S
> #+%Y.%m.%d.%H:%M:%S
> }
root@SomeHost:~#
root@SomeHost:~# date_converted=`convert_date $date`
root@SomeHost:~# echo $date_converted
2021-10-13 15:03:25
root@SomeHost:~# line_converted=`convert_date $line`
root@SomeHost:~# echo $line_converted
2015-03-25 11:34:19
root@SomeHost:~# diff_dates $date_converted $line_converted
701231085635
Could I remove TZ=UTC date -d @$((TS1-TS2)) +%g%m%d%H%M%S
and get better conversion with something else? With echo $(($TS2-$TS1))
I could get time in seconds, but I don't know how to convert that to a date that doesn't start with 1970...
Maybe (almost certainly) I'm doing this completely wrong and there is much less complicated way of doing this.
I pieced this question together over 2 hours so if there is something that doesn't make sense please point it out and I will try to fix it.
line="150325113419
in epoch format?