R programming language provides several functions to deal with date and time. Formatting and converting dates from one format to another is a frequent task any developer could face. The general rule of thumb for dealing with date/time in R is to use the simplest technique possible. Otherwise, it gets ugly and complex.
R Date Format
To format the dates in R, use the format() function. The format() method accepts an R object and the format in which we want the output. The format() method provides you with formatting an R object for pretty printing. The Dates in R are expressed as the number of days since 1970-01-01. If you want the dates before 1970-01-01, you should use the negative values.
If your dates are stored as characters, you have to provide as.Date() function with your vector of dates and the format they are currently stored in.
To get today’s date, use the Sys.Date() method. The get the current date and time in R, use the date() method.
Example of date formats in R
Let’s get today’s date using Sys.Date() method.
today <- Sys.Date() today
Now, To get the textual format of this date, use the format() function.
today <- Sys.Date() format(today, format="%B %d %Y")
The format() method accepts today as R Object and format as the format we want in return. Run the program.
 "March 17 2021"
Get abbreviated weekday from the date in R
To get the abbreviated weekday from the date in R, use the %a.
today <- Sys.Date() format(today, format="%a")
Get Full Month from a Date in R
To get the full month from a date in R, use the %B in the format() function.
today <- Sys.Date() format(today, format="%B")
Get the Day of the month
To get the month from a date in R, use the %d in the format() function.
today <- Sys.Date() format(today, format="%d")
Get the Month from a date in R
To get the month from a date in R, use the %m in the format() function.
today <- Sys.Date() format(today, format="%m")
Various Date formats in R
|%a||Abbreviated weekday||Sun, Mon|
|%A||Full weekday||Sunday, Monday|
|%b or %h||Abbreviated month||Sep, Nov|
|%B||Full month||September, November|
|%d||Day of the month
|%j||Day of the year
with Sunday as the first day of the week
Sunday is 0
with Monday as the first day of the week
|%y||Year without century
|%Y||Year with century
00 to 68 prefixed by 20
69 to 99 prefixed by 19
|%D||Date formatted %m/%d/%y||09/10/93, 11/20/93|
Monday is 1
That is it for date formatting in R.
Krunal Lathiya is an Information Technology Engineer by education and web developer by profession. He has worked with many back-end platforms, including Node.js, PHP, and Python. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language. Krunal has written many programming blogs, which showcases his vast expertise in this field.