1

I have the following format of Date which is a database query result:

yyyy-mm-dd-hh.mm.ss.mmmmmm

example

myDate=2014-03-28-23.05.04.000000

I tried

$(( ( $(date +%s) - $(date -d "${myDate}" +%s) ) /(24 * 60 * 60 ) ))

But it gives me date not valid error.

I want to find out how many days its been since myDate. I need to have the result not rounded up or down as an example the result could be 2.5 days or 1.6 etc. based on the number of hours, minutes and seconds.

ComeRun
  • 921
  • 1
  • 20
  • 38
  • Possible duplicate of [How to find the difference in days between two dates?](https://stackoverflow.com/questions/4946785/how-to-find-the-difference-in-days-between-two-dates) – jww Apr 29 '18 at 21:22

2 Answers2

3

Just need to tweak the separators a bit:

$ date -d "$(sed 's/-/ /3; s/\./:/1; s/\./:/1' <<< $myDate)" +%s
1396062304

Change the 3rd hyphen to a space, and then change the first dot to a colon, and then change the (now) first dot to a colon.

Then

$ echo $(( ( $(date +%s) - $(date -d "$( sed 's/-/ /3; s/\./:/1; s/\./:/1' <<< $myDate)" +%s) ) /(24 * 60 * 60 ) ))
2
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
2

You have to use date -f to specify an input format. For instance

date -d -f %Y-%m-%d-%h.%m.%S.?????? "$PmyDate}" +%s

(I'm not sure what mmmmmm specifies) This format is using the strptime function; a reference for this is http://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html.

cheshircat
  • 183
  • 1
  • 10
  • 1
    Presumably mmmmmm is microseconds – Digital Trauma Apr 01 '14 at 01:38
  • Ah, well I don't know if strptime has a format specifier for that. You might want to just strip it off if it's not going to make so much of a difference. (You're working with days; you don't need to be that precise). – cheshircat Apr 01 '14 at 01:51
  • This appears to be for the BSD `date`: "-f Use input_fmt as the format string to parse the new_date provided...". But the question is tagged Linux, so I would expect GNU `date` to be in effect, in which case `-f` means read dates from file - not what you want at all. – Digital Trauma Apr 01 '14 at 02:39
  • GNU date doesn't have an option for that. Oh well, I this you need to use sed like glenn jackman – cheshircat Apr 01 '14 at 02:50