Hi, In this tutorial, you will learn, how to convert the string to date format using the R Programming language. 

Whenever you read a dataset from any data source, the date format can be read as character format in R Programming. And at the same, the different people or data source will use the different date format. 

So if you want to write filter condition using dates, then you must convert a string to date.

The default date format of R Programming is year-month-date(2019-01-20). 

You can get the System date using.

Sys.Date()

Output:
"2019-01-03"

 

as.Date

You can use the as.Date() function to convert the string to date in R Programming.

as.Date("2019-01-20")

You can increment the date to check whether it is converted to date format or not using.

as.Date("2019-01-20")+1

Output:
"2019-01-21"

If your string is year-month-date fromat then as.Date() will work fine without any error.

However if you have any other format, then as.Date() function will throw error. Say, for example, take the Oracle Date format.

22-JAN-19

The Oracle had the date-month-year format.


22 - Date
JAN- First 3 letter of a month
19 - Last two digit of a year.

If you pass this value to as.Date() function, then it will throw error.

as.Date("22-JAN-19")

Output:
Error in charToDate(x) :
 character string is not in a standard unambiguous format

So to convert this date format to R Programming date format, then you must mention the format of the input string.

as.Date("22-JAN-19",format="%d-%b-%y")

Output:
"2019-01-22"

You can check whether the Oracle date format is converted to R Programming date format by adding dates.

as.Date("22-JAN-19",format="%d-%b-%y")+2

Output:
"2019-01-24"

That's all. You have converted the string to date in R Programming.

Various Date Conversion Format are listed below.
 

Code Meaning Code Meaning
%a Abbreviated weekday %A Full weekday
%b Abbreviated month %B Full month
%c Locale-specific date and time %d Decimal date
%H Decimal hours (24 hour) %I Decimal hours (12 hour)
%j Decimal day of the year %m Decimal month
%M Decimal minute %p Locale-specific AM/PM
%S Decimal second %U Decimal week of the year (starting on Sunday)
%w Decimal Weekday (0=Sunday) %W Decimal week of the year (starting on Monday)
%x Locale-specific Date %X Locale-specific Time
%y 2-digit year %Y 4-digit year
%z Offset from GMT %Z Time zone (character)