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-
Specifier |
Description |
---|---|
%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:
# today date date<- Sys.Date ()
# abbreviated Day format (date,format= "%a" )
# full Day format (date,format= "%A" )
# weekday 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:
# today date date<- Sys.Date ()
# default format yyyy-mm-dd date # day in month format (date,format= "%d" )
# month in year format (date,format= "%m" )
# abbreviated month format (date,format= "%b" )
# full month format (date,format= "%B" )
# Date 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:
# today date date<- Sys.Date ()
# year without century format (date,format= "%y" )
# year with century format (date,format= "%Y" )
# century format (date,format= "%C" )
|
Output
[1] "22"
[1] "2022"
[1] "20"