Reputation: 1036
I have data in Character format like 'Feb-20'. I need to convert it to '2020-02-29' R Date format. Code should be generic to convert any month and return last day of month.
repmonth <- 'Feb-20'
Upvotes: 1
Views: 172
Reputation: 13319
We can use strptime
:
strptime('Feb-20',format="%b-%d", tz="UTC")
[1] "2020-02-20 UTC"
Or using lubridate
as @Neem Kamal suggests:
lubridate::ymd(paste0("2020-","Feb-20"))
EDIT:
To return the last day of the month:
lubridate::ceiling_date(strptime('Feb-20',format="%b-%d", tz="UTC"),"month") -1
[1] "2020-02-29 23:59:59 UTC"
Works for March as well:
lubridate::ceiling_date(strptime('Mar-20',format="%b-%d", tz="UTC"),"month") -1
[1] "2020-03-31 23:59:59 UTC"
Drawbacks: It returns time too.
Upvotes: 2
Reputation: 1076
Here you go,
library(lubridate)
repmonth <- 'Feb-20'
rollback(ymd(paste0("2020-",repmonth) ) + month(1), roll_to_first = F)
The above will give what exactly you are looking for. The last day of the month whether it's leap year or not.
Upvotes: 0
Reputation: 224
29 is fixed? You could use the lubridate package:
lubridate::myd(paste0('Feb-20','-29'))
Upvotes: 0