Dates are represented by Date class. Internally the dates are stored as the no of days since 1970 January 1st.
# convert into a Date
x<-'1970-1-1'
class(x)## [1] "character"
y<-as.Date(x)
y## [1] "1970-01-01"
class(y)## [1] "Date"
# We can see internal representation of a Date object by using unclass().
unclass(y)## [1] 0
unclass(as.Date('1970-1-2'))## [1] 1
unclass(as.Date('1969-12-31'))## [1] -1
weekdays(y) # it tells us what day of the week a given time is or a given day is## [1] "Thursday"
months(y) # it tells us what month that time or date is## [1] "January"
quarters(y) # it tells us the quarter number, Q1 means Jan through Mar, Q2 means Apr through Jun,.......## [1] "Q1"
Times are represented by POSIXlt or POSIXct class. Internally the times are stored as the no of seconds since 1970 January 1st.
x<-('2021-1-26 18:02')
y<-as.POSIXct(x)
y## [1] "2021-01-26 18:02:00 PST"
unclass(y) # it is useful type of class if you want to store times in a data frame or something like because it is like a big integer vector## [1] 1611712920
## attr(,"tzone")
## [1] ""
z<-as.POSIXlt(x) # to store time as a list underlying
z## [1] "2021-01-26 18:02:00 PST"
names(unclass(z))## [1] "sec" "min" "hour" "mday" "mon" "year" "wday" "yday"
## [9] "isdst" "zone" "gmtoff"
# y$sec isn't possible
z$sec## [1] 0
a<-Sys.time() # returns the system's idea of the current date with time
class(a)## [1] "POSIXct" "POSIXt"
a<-as.POSIXlt(a)
class(a)## [1] "POSIXlt" "POSIXt"
a$sec## [1] 3.67102
strptime function converts dates (written in character string format) into date or time object
d<-c('January 26,2021 19:57','January 1,2021 0:00')
x<-strptime(d,'%B %d,%Y %H:%M') # formatting string: to look at help page (?strptime)
x## [1] "2021-01-26 19:57:00 PST" "2021-01-01 00:00:00 PST"
class(x)## [1] "POSIXlt" "POSIXt"
Operation: you canโt mix different classes.
x<-as.Date('2021-1-26')
y<-as.POSIXlt('2021-1-1 0:00')
#x-y: we will get an error
x<-as.POSIXlt(x)
x-y## Time difference of 24.66667 days
# If you want more control over the units when finding the above difference in times, you can use difftime(), which allows you to specify a 'units' parameter.
difftime(x,y,units='hours')## Time difference of 592 hours
x>y## [1] TRUE