user1220402 user1220402 - 2 months ago 8
Bash Question

From difference between two date time get the another time back

I have the following:
seconds (s), minutes (m), hours (h), and days (d), as described in the
following: and want to convert it into Date&Time by subtracting given time from current date time.
DATE1- DATE2= DIFF, want to calculate DATE2 by giving DATE1 and DIFF .

Means if current time is 2016-04-02T12:00:00 and given input is 23H60M then output should be 2016-04-01T12:00:00, and it can be 23D24H,can be 23M20S...
400d - Only days (d) displayed

20d23h - days (d) and hours (h) displayed

14h33m - hours (h) and minutes (m) displayed

10m59s - minutes (m) and seconds (s) displayed

Answer

you can try something like this;

#!/bin/bash
input=$(echo $1 | tr '[:lower:]' '[:upper:]')

if [[ $input == *"D"* ]]
then
input=$(echo $input | sed 's/D/ days ago /g')
fi

if [[ $input == *"H"* ]]
then
input=$(echo $input | sed 's/H/ hours ago /g')
fi

if [[ $input == *"M"* ]]
then
input=$(echo $input | sed 's/M/ minutes ago /g')
fi

if [[ $input == *"S"* ]]
then
input=$(echo $input | sed 's/S/ seconds ago /g')
fi
echo $input


CURRENTDATE="$(date +%Y-%m-%d-%H:%M:%S)"
echo $CURRENTDATE
OLDERDATE="$(date "+%Y-%m-%d-%H:%M:%S" -d "$input")"
echo $OLDERDATE
Comments