I am trying to convert a character to date format, but "day" is replaced with 4 digits.
> mydate="20/3/20"
> mydate=as.Date(mydate)
> mydate
[1] "0020-03-20"
This didn't happen a few days ago, only now as I re-run an old script. I don't know if this has to do with me upgrading recently to R version 3.6.3.
I tried to remove the "00" with gsub, but it turns the date back to character again.
> mydate=gsub("00","",mydate)
> class(mydate)
[1] "character"
Does anyone know how I can fix that with mydate
remaining as date, or why this happens?
Thank you in advance
The default format for Date
class is "%Y-%m-%d"
i.e. 4 digit year followed by a dash, followed by two digits, then a dash and two digits. Any other format, we need to specify the format
argument in as.Date
as.Date(mydate, "%d/%m/%y")
#[1] "2020-03-20"
We need to be very careful with two-digit year as it can lead some strange output. It is better to have 4 digit year