Skip to content

question about difference in date objects

4 messages · Phil Smith, Karl Ove Hufthammer, Gabor Grothendieck +1 more

#
Hi R Community:

I want to take the difference in two dates:

dt2 - dt1.

But, I want the answer in months between those 2 dates.

Can you advise me?

Please respond to: pzs6 at cdc.gov

Thank you!
Phil Smith
Centers for Disease Control and Prevention
#
On Mon, 02 Nov 2009 06:29:54 -0500 Phil Smith
<philipsmith at alumni.albany.edu> wrote:
What do you mean by 'months'? The number of days in a month vary, so the 
number of months between two dates is not defined. But if you're willing 
to think of a month as 30 days, you just have to divide by 30:

d=dt2-dt1
d/30

or

as.numeric(d)/30

if you want to avoid the (wrong) textual description.
#
Since months have different lengths the difference in months is not
well defined but lets define it as the difference between the first of
the month of two dates. In that case we can use as.yearmon of the zoo
package.  It converts to year/months, dropping days, using an internal
representation of year + 0 for Jan, year + 1/12 for Feb, year + 2/12
for Mar, etc.  so differencing and multiplying by 12 gives the number
of months:
[1] "2009-11-02"
[1] "2009-07-25"
[1] 4


On Mon, Nov 2, 2009 at 6:29 AM, Phil Smith
<philipsmith at alumni.albany.edu> wrote:
#
On Mon, 2 Nov 2009, Phil Smith wrote:

            
How long is a month?

difftime() can give you an answer in days, which might suffice if you 
define a month as a number of days.  Another idea is to use (untested)

getMonth <- function(x)
{
    xx <- as.POSIXlt(x)
    12*xx$year + xx$mon + (xx$mday-1)/31
}

which will convert to a (fractional) number of months since 
1900-01-01, and that can be differenced.