How to use the base R as.POSIXlt function In R Language

R




# Example dates
date1 <- as.POSIXlt("2021-01-01")
date2 <- as.POSIXlt("2023-08-01")
 
# Calculate the difference in years
years_diff <- date2$year - date1$year
years_diff


Output:

[1] 2

methods



How to calculate Years between Dates in R ?

To calculate the number of years between two dates we have several methods. In this article, we will discuss all the methods and their examples of how to calculate the number of years or the difference of years between two dates in the R Programming Language.

Table of Content

  • Method 1: Using the seq() function
  • Method 2: Using the difftime function
  • Method 3: Using the base R as.POSIXlt function

Example:

Input: 

Date_1 = 2020/02/21

Date_2 = 2023/03/21

Output:

3

Explanation: 

In Date_1 and Date_2 have three years difference in year.

Here we will use the seq() function to get the result. This function is used to create a sequence of elements in a Vector.

Syntax: 

length(seq(from=date_1, to=date_2, by=’year’)) -1  

Similar Reads

Method 1: Using the seq() function

...

Method 2: Using the difftime function

Example 1:...

Method 3: Using the base R as.POSIXlt function

...