简体   繁体   中英

Convert Character Date format to R Date

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'

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.

29 is fixed? You could use the lubridate package:

lubridate::myd(paste0('Feb-20','-29'))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM