Date and time format in R

Handle date in R

As for the other programming languages, date manipulation is particular in R and is based on the number of days since the 1st January 1970. This date is used on many programming languages and is known as the Unix time stamp. In R, date has its own data class, that can help to deal with geographic variations.

Get current date in R

At first, we will get the current date on our environment. To get this, we will use the Sys.Date() function. It's a basic function that return the date with the following format: Year-Month-Day.

Here is an example:

[1] "2019-04-02"

The Sys.Date() function return an object with the Date class, that will be used on our scripts. Note that we can use the date() function that will return the date at the English format and add system time too.

[1] "Tue Apr 2 11:56:44 2019"

Date format in R

We can format the date object to used them with more conventional format. Here is an example of the usable variables.

Symbol Usage Example
%d day as a number (0-31) 02
Abbreviation day of the week
Full day of the week
%m Month in numeric character (00-12) 04
Abbreviation of the month
Full name of the month
Year number 19

To use these different format, you have to use the format() function that will convert our object Date. Here is an example:

format(Sys.Date(), format="%A %d %B %Y")
[1] "Tuesday 02 april 2019"

Note that you have to use the as.character() function to manipulate theses dates as character strings.

Convert a character object to date object

To manipulate date objects, you have to transform an object to a date object with the as.Date() function. Here is an example of this function:

as.Date(x = myCharacterString, format = myFormat)

You have to mention the character string format to manipulate it. For example:

as.Date(x = "02-04-2019", format = "%d-%m-%Y")

Note that you not have to edit the format attribute. The default format will be