How to Use Date Formats in R
In this article, we will be looking at the approaches to using the date formats in the R programming language,
R programming language provides several functions that deal with date and time. These functions are used to format and convert the date from one form to another form. R provides a format function that accepts the date objects and also a format parameter that allows us to specify the format of the date we needed. R provides various format specifiers which are mentioned below in Table-
%a
|
Abbreviated weekday
|
%A
|
Full weekday
|
%b
|
Abbreviated month
|
%B
|
Full month
|
%C
|
Century
|
%y
|
Year without century
|
%Y
|
Year with century
|
%d
|
Day of month (01-31)
|
%j
|
Day in Year (001-366)
|
%m
|
Month of year (01-12)
|
%D
|
Data in %m/%d/%y format
|
%u
|
Weekday (01-07) Starts on Monday
|
Note:To get the Today date, R provides a method called sys.Date() which returns the today date.
Weekday:
In this, we will look into the %a, %A, and %u specifiers which give the abbreviated weekday, full weekday, and numbered weekday starting from Monday.
Example:
R
date<- Sys.Date ()
format (date,format= "%a" )
format (date,format= "%A" )
format (date,format= "%u" )
|
Output
[1] "Sat"
[1] "Saturday"
[1] "6"
Date:
Let’s look into the day, month, and year format specifiers to represent dates in different formats.
Example:
R
date<- Sys.Date ()
date
format (date,format= "%d" )
format (date,format= "%m" )
format (date,format= "%b" )
format (date,format= "%B" )
format (date,format= "%D" )
format (date,format= "%d-%b-%y" )
|
Output
[1] "2022-04-02"
[1] "02"
[1] "04"
[1] "Apr"
[1] "April"
[1] "04/02/22"
[1] "02-Apr-22"
Year:
We can also able to format the year in different forms. %y, %Y, and %C are the few format specifiers that return the year without century, a year with century, and century of the given date respectively.
Example:
R
date<- Sys.Date ()
format (date,format= "%y" )
format (date,format= "%Y" )
format (date,format= "%C" )
|
Output
[1] "22"
[1] "2022"
[1] "20"
Last Updated :
01 Aug, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...