LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Offline method required to find out number of days since a certain date! (https://www.linuxquestions.org/questions/linux-general-1/offline-method-required-to-find-out-number-of-days-since-a-certain-date-849884/)

linustalman 12-13-2010 03:49 AM

Offline method required to find out number of days since a certain date!
 
Hi.

What offline method is there of finding out days since a certain date. Example: How would someone find the number of days from 1-Jan-2003 to 7-Dec-2010? Could someone write a script that takes in the 2 dates and output the number of days?

Thanks.

colucix 12-13-2010 04:49 AM

What have you tried so far? Basically you need to convert the two dates in seconds since the system reference time (epoch for unix shells), subtract them and divide the result by 86400. If you're interested in the fractional part you can use either bc or awk, since the shell doesn't do floating point arithmetic.

Bertical 12-13-2010 07:11 AM

Code:

[cpt_scarlet@spectrum:~] $ ((datediff=(( `date -u -d "2010-07-12" +%s` - `date -u -d "2003-01-01" +%s`))))
[cpt_scarlet@spectrum:~] $ echo $((datediff / 86400 ))
[cpt_scarlet@spectrum:~] $ 2749


Bertical 12-13-2010 06:55 PM

Or it might be

Code:

[cpt_scarlet@spectrum:~] $ ((datediff=(( `date -u -d "2010-12-07" +%s` - `date -u -d "2003-01-01" +%s`))))
[cpt_scarlet@spectrum:~] $ echo $((datediff / 86400 ))
[cpt_scarlet@spectrum:~] $ 2897

please check before handing in homework.

linustalman 12-14-2010 03:20 AM

Quote:

Originally Posted by Bertical (Post 4190359)
Or it might be

Code:

[cpt_scarlet@spectrum:~] $ ((datediff=(( `date -u -d "2010-12-07" +%s` - `date -u -d "2003-01-01" +%s`))))
[cpt_scarlet@spectrum:~] $ echo $((datediff / 86400 ))
[cpt_scarlet@spectrum:~] $ 2897

please check before handing in homework.

Hi Bertical. No, it is not homework. I am just curious as to how to calculate it. I don't understand how to run your solution though.

colucix 12-14-2010 03:52 AM

You can either write a script or a function passing the two dates as arguments. Example, if you define a function:
Code:

function datediff () {
  echo $(( ($(date -ud "$2" +%s) - $(date -ud "$1" +%s)) / 86400 ))
}

then you can simply launch a command like this:
Code:

$ datediff 1-Jan-2003 7-Dec-2010
2897

The two dates must be in a standard format recognized by the date command. See info date for details.


All times are GMT -5. The time now is 04:38 PM.