0

I am writing a script where I am looking for help. I am using date format in my script as below (YYYY MM DD HH MM):

$ echo $DT
202002252216

Now my requirement is to compare two dates listed in the file and calculate output in hours.

cat /home/postgres/pglinux_mm_cfg
MM_START=202002261015
MM_END=202002261530
MM_SERVER=pglinux 

Here is my script, timediff.sh

ENV=/home/postgres
MM_START=`grep MM_START ${ENV}/\`hostname\`_mm_cfg |awk -F"=" '{print $2}'`
MM_END=`grep MM_END ${ENV}/\`hostname\`_mm_cfg |awk -F"=" '{print $2}'`

MPHR=60
STARTIME=$(date +%Y%m%d%H%M -d ${MM_START})
ENDTIME=$(date +%Y%m%d%H%M  -d ${MM_END})
MINUTES=$(( ($ENDTIME - $STARTIME) / $MPHR ))

echo $STARTIME $ENDTIME $MINUTES

How to get date difference between MM_END AND MM_START in day's and hours?

I am using ksh.

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
Durga
  • 17
  • 1
    Double-quote your variables when you use them ("$MM_START" instead of just $MM_START, for example). Also, start your script with #!/bin/ksh or whatever fits the path for your shell. Finally, do not use all capitals for your variable names - they are likely to clash with existing reserved names - instead use lowercase. – Chris Davies Feb 25 '20 at 22:51

2 Answers2

0

Should work (but untested) on ksh:

echo "$MM_START", "$MM_END", $(( ($(date -d"${MM_END:0:8} ${MM_END:8}" +%s) - $(date -d"${MM_START:0:8} ${MM_START:8}" +%s) )/ 60 ))
202002261015, 202002261530, 315

This uses shell's

  • "arithmetic expansion" $((...)) to perform the difference and division

  • "command substitution" $(...) (twice, for the two date commands) that " allows the output of a command to replace the command name" (c.f. man bash)

  • "Parameter Expansion / Substring Expansion" to extract substrings from a variable.

After all, it produces two "epoch seconds" that are subtracted, and the result divided by 60 to get at minutes. Be aware that bash only performs integer arithmetics (can't speak for ksh).

RudiC
  • 8,969
  • Hello RudiC, Thank you so much for piece of code, It is working fine, tested couple of time. How do i Understand the code $(( ($(date -d"${MM_END:0:8} ${MM_END:8}" +%s) - $(date -d"${MM_START:0:8} ${MM_START:8}" +%s) )/ 60 )) . Kindly explain – Durga Feb 26 '20 at 19:05
  • See my edit ... – RudiC Feb 26 '20 at 19:59
  • RudiC, Thank you so much. it is working fine. My apologies for very late reply – Durga Apr 30 '20 at 21:24
0

This may not be what you had in mind, but this is much simpler with a proper programming language. For example with PHP:

<?php
$o1 = date_create('202002261015');
$o2 = date_create('202002261530');
$o3 = date_diff($o2, $o1);
echo 'days: ', $o3->d, ', hours: ', $o3->h, "\n";

Result:

days: 0, hours: 5

https://php.net/function.date-diff

Zombo
  • 1
  • 5
  • 44
  • 63