-1

I need time elapsed since $var

$var= [19:11:27 19:34:09]  

$var was created from

date "+[%y:%m:%d %T]"
Romeo Ninov
  • 6,538
  • 1
  • 22
  • 31
Hugo Slop
  • 11
  • 3

2 Answers2

1

If mktime function of awk is available, how about:

awk -v var='[19:11:28 14:34:09]' '
BEGIN {
    split(var, a, "[^0-9]")
    elapsed = systime() - mktime(a[2]+2000" "a[3]" "a[4]" "a[5]" "a[6]" "a[7])
    d = int(elapsed / 86400)
    h = int((elapsed - d * 86400) / 3600)
    m = int((elapsed - d * 86400 - h * 3600) / 60) 
    printf("%d days %d hours %d mins passed.\n", d, h, m)
}'
tshiono
  • 21,248
  • 2
  • 14
  • 22
  • How do i use this... i put it in a script..and errors... i see this looks like unix... idk how to use it. Also seems unnecessary... d= h= and m=. – Hugo Slop Nov 28 '19 at 05:49
  • Please copy the code above and save as a file e.g. `file.awk`, then execute `bash file.awk` on the command line. If you still have an error, please let me know including the error message. BR. – tshiono Nov 28 '19 at 06:46
0

Few alternative,

If you can change the setting of var:

You are better using the SECONDS bash variable. You can then use bash math to calculate difference, and format the output.

 # Instead of var=...
START=$SECONDS
... do something that take long time
... to executed
FINISH=$SECONDS
ELAPSED=$((FINISH-START))

If you can NOT change the setting of var:

You will have to convert var to a format that date will accept, and use the methods suggested in the comments. Minimal effort to convert to ISO YYYY-MM-DD HH:MM:SS

VX=20${var/:/-}   # Replace first : with -, add 2000 to the yy part
VX=${var/:/-}     # Replace Second : with -
START=$(date -d "$VX" +'%s')
FINISH=(date +'%s')
ELAPSED=$((FINISH-START))
dash-o
  • 13,723
  • 1
  • 10
  • 37
  • 1
    @HugoSlop The most difficult thing about your question is how to parse the date format you have (`[%y:%m:%d %T]`) into something more useful. If it's possible to *start* with a simpler representation -- like the number of seconds since the shell started (`$SECONDS`), the task gets much easier. Seconds since the unix epoch (`date +%s`) would also work well. – Gordon Davisson Nov 28 '19 at 06:15
  • 1
    @HugoSlop I've fixed the formatting, and added logic for case that the value of 'var' can not be modified. – dash-o Nov 28 '19 at 13:33