# How to calculate number of days between two dates in R ?

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

## Working with Dates in R

Dates play a crucial role in data analysis, and figuring out the time difference between two dates is a typical job. Calculating the number of days between two dates in R is simple owing to built-in functions and date manipulation packages. In this post, we’ll look at many methods for calculating the number of days between two dates in R.

Example:

`Input: Date_1 = 2020/03/21 Date_2 = 2020/03/22Output: 1Explanation:In Date_1 and Date_2 have only one day difference. So output will be 1.`

Here we will use the 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.

## 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 subtracting 1 because` `# we dont need to include current day.` `length``(a)-1`

Output:

`[1] 1`

## R

 `# Example dates` `date1 <- ``as.Date``(``"2023-07-15"``)` `date2 <- ``as.Date``(``"2023-07-31"``)`   `# Calculate the difference in days using subtraction` `num_days <- date2 - date1`   `# Print the result` `print``(num_days)`

Output:

`Time difference of 16 days`

## R

 `# Example dates` `date1 <- ``as.Date``(``"2023-07-15"``)` `date2 <- ``as.Date``(``"2023-07-31"``)`   `# Calculate the difference in days using difftime()` `days_diff <- ``difftime``(date2, date1, units = ``"days"``)`   `# Extract the number of days as numeric value` `num_days <- ``as.numeric``(days_diff)`   `# Print the result` `print``(num_days)`

Output:

`[1] 16`

## R

 `calendar <- ``create.calendar``(``'my_calendar'``)`   `bizdays``(from = ``'2022-01-01'``, to = ``'2022-01-31'``, cal = business_calendar)`

Output:

`[1] 30`

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next