ay4you
ay4you

Reputation: 21

subtracting dates with specific format

i have search for a solution to my shell date subtraction issue with no joy so here goes. i have a date format like so %m%d%H%M%S which is "0102231203" and the second %Y%m%d%H%M%S, i can take the year off the second one and do a normal subtraction but when it is over a day it becomes an issue with the time being incorrect. here is what i have tried so far

BTT=0102234500

TPP=0102233635 (after removing the year)

BT=date -d ${BTT}

TP=date -d ${TPP}

and

BT=date -d $BTT +%m%d%H%M%S

TP=date +%m%d%H%M%S -d ${TPP}

date: invalid date `0102234500'

date: invalid date `0102233635'

BT=date -d @${BTT} +%m%d%H%M%S

TP=date +%m%d%H%M%S -d @${TPP}

weird output

0329071355

0329072820

BT=date -d @${BTT}

TP=date -d @${TPP}

Thu Mar 29 07:13:55 BST 1973

Thu Mar 29 07:28:20 BST 1973

even changed it to add the year to both still

BTT=20130102234500

TPP=20130102233635

BT=date -d @${BTT}

TP=date -d @${TPP}

Fri Jul 19 08:53:55 GMT 639867

Fri Jul 19 09:08:20 GMT 639867

how do i resolve this issue. tnx

Upvotes: 0

Views: 71

Answers (1)

Pilou
Pilou

Reputation: 1478

The -d option of date accept human readable string so if you can have full length date you can do :

me@server:/tmp$ BTT=`date +"%Y-%m-%d %H:%M:%S"`
me@server:/tmp$ TPP=`date +"%Y-%m-%d %H:%M:%S"`
me@server:/tmp$ echo $((`date -d "$TPP" +%s`-`date -d "$BTT" +%s`))
3

With your datas :

me@server:/tmp$ BTT="2013-01-02 23:45:00"                          
me@server:/tmp$ TPP="2013-01-02 23:36:35"                          
me@server:/tmp$ echo $((`date -d "$BTT" +%s`-`date -d "$TPP" +%s`))
505

With the results in seconds.

Upvotes: 1

Related Questions