Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)
edited by

I have two dates let´s say 14.01.2013 and 26.03.2014.

I would like to get the difference between those two dates in terms of weeks(?), months(in example 14), quarters(4) and years(1).

Do you know the best way to get this?

1 Answer

0 votes
by
edited by

To get the difference between dates in weeks, months, quarters, and years, you can use the following functions from the zoo and lubridate packages as follows:

Weeks:

library("zoo")

library("lubridate")

difftime(strptime("26.03.2014", format = "%d.%m.%Y"),

         strptime("14.01.2013", format = "%d.%m.%Y"),units="weeks")

Time difference of 62.28571 weeks

Months:

(as.yearmon(strptime("26.03.2014", format = "%d.%m.%Y"))-

    as.yearmon(strptime("14.01.2013", format = "%d.%m.%Y")))*12

[1] 14

Quarters:

(as.yearqtr(strptime("26.03.2014", format = "%d.%m.%Y"))-

    as.yearqtr(strptime("14.01.2013", format = "%d.%m.%Y")))*4

[1] 4

Years:

year(strptime("26.03.2014", format = "%d.%m.%Y"))-

  year(strptime("14.01.2013", format = "%d.%m.%Y"))

[1] 1

If you want to explore more in R programming then watch this R programming tutorial for beginners:

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...