R Date Format: How to format dates using format()

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

Output

[1] "2021-03-17"

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.

Output

[1] "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")

Output

[1] "Wed"

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")

Output

[1] "March"

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")

Output

[1] "17"

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")

Output

[1] "03"

Various Date formats in R

Conversion specification Description Example
%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
01-31
10, 20
%j Day of the year
001-366
250, 310
%m Month
01-12
09, 11
%U Week
01-53
with Sunday as the first day of the week
35, 45
%w Weekday
0-6
Sunday is 0
0, 4
%W Week
00-53
with Monday as the first day of the week
21, 27
%x Date, locale-specific
%y Year without century
00-99
84, 05
%Y Year with century
on input:
00 to 68 prefixed by 20
69 to 99 prefixed by 19
1984, 2011
%C Century 19, 20
%D Date formatted %m/%d/%y 09/10/93, 11/20/93
%u Weekday
1-7
Monday is 1
7, 4

That is it for date formatting in R.

Leave a Comment