LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to subtract two dates in a file to get number of days? (http://www.linuxquestions.org/questions/linux-newbie-8/how-to-subtract-two-dates-in-a-file-to-get-number-of-days-818004/)

btacuso 07-04-2010 06:35 PM

How to subtract two dates in a file to get number of days?
 
I have a sample file with six fields delimited by commas below:

1astname1,firsname1 , 216057926,102,07/03/10,07/04/10
lastname2,firstname2 , 211968262,105,07/01/10,07/04/10
lastname3,firstname3, 214783220,113,06/29/10,07/04/10

field 5 is first date
field 6 is last date

I need to subtract field6 - field5 to get the number of days and then append it as field7 to the file. Desired result is below:

1astname1,firsname1 , 216057926,102,07/03/10,07/04/10,1
lastname2,firstname2 , 211968262,105,07/01/10,07/04/10,3
lastname3,firstname3, 214783220,113,06/29/10,07/04/10,5

I appreciate any help.

colucix 07-04-2010 07:04 PM

You can simply use the date command and the bash arithmetic operator. Date differences are usually made in seconds since epoch units, then we can apply any conversion to days, hours and so on by means of the proper conversion factor. Since you don't need fractional parts of the day, bash (integer) arithmetic is enough. An example of the date command:
Code:

$ my_date="07/04/10"
$ date -ud $my_date +%s
1278201600

Note the -u option to work with UTC time. It's useful if by chance the two dates span across the day of change from/to Daylight Saving Time.

btacuso 07-13-2010 12:33 PM

Thanks a lot. I was able to fix it thru this guide.


All times are GMT -5. The time now is 03:54 AM.