Skip to content
Related Articles

Related Articles

Improve Article
How to calculate number of days between two dates in R ?
  • Last Updated : 28 Apr, 2021

In this article, we will discuss how to Find the number of days between two dates in the R programming language. 

Example:

Input:

 Date_1 = 2020/03/21

 Date_2 = 2020/03/22



Output: 1

Explanation: In Date_1 and Date_2 have only one difference in day.So output will be 1.

Here we will use seq() function to get the result. This function is used to create a sequence of elements in a Vector. To get the number of days length() function is employed with seq() as an argument.

Syntax: length(seq(from=date_1, to=date_2, by=’day’)) -1

Parameter:

  • seq is function generates a sequence of numbers.
  • from is starting date.
  • to is ending date.
  • by is step, increment.

Example 1:

R




# creating date_1 variable 
# and storing date in it.
date_1<-as.Date("2020-10-10")
  
# creating date_2 variable
# and storing date in it.
date_2<-as.Date("2020-10-11")
.
a = seq(from = date_1, to = date_2, by = 'day')
  
# Here we are finding length of 
# a and we are subtrating 1 because
# we dont need to include current day.
length(a)-1

Output:

1

Example 2:

R




# creating date_1 variable 
# and storing date in it.
date_1<-as.Date("2020-01-10")
  
# creating date_2 variable 
# and storing date in it.
date_2<-as.Date("2020-02-20")
  
a = seq(from = date_1, to = date_2, by = 'day')
  
# Here we are finding length of a 
# and we are subtrating 1 because we
# dont need to include current day.
length(a)-1

Output:

41




My Personal Notes arrow_drop_up
Recommended Articles
Page :