1

I am converting following format to date from character

  January 2016

I want to convert it to following format

   201601

I am using following code

    df$date <- as.Date(df$date,"%B %Y")

But it returns me NA values. I have even set the locale as follows

    lct<- Sys.getlocale("LC_TIME")
    Sys.setlocale("LC_TIME",lct)

But it gives me NA values. How to fix it

Neil
  • 7,937
  • 22
  • 87
  • 145
  • Possible duplicate of [Convert month year to a date in r](http://stackoverflow.com/questions/26697399/convert-month-year-to-a-date-in-r) – Ronak Shah Mar 22 '17 at 06:26

1 Answers1

2

We can do this easily with as.yearmon and format

library(zoo)
format(as.yearmon(str1), "%Y%m")
#[1] "201601"

If we are going by the as.Date route, then 'Date' requires day also, so, paste a day and then use format after converting to 'Date'

format(as.Date(paste(str1, '01'), "%B %Y %d") , "%Y%m")

data

str1 <- "January 2016"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • how to find difference of above date format with current date e.g 201601 and 201510 should be in days – Neil Mar 22 '17 at 06:42
  • @Neil If you really wanted difference, then it is better to be in `Date` or in `yearmon` i.e. `as.yearmon(str1) - as.yearmon("201601", "%Y%m") #[1] 0` – akrun Mar 22 '17 at 06:45