Using the "format" argument in as.Date ()

I am trying to convert "07,29,30" to date format using as.Date () in R.

(Note that the string format is "mm, dd, yy", July 29, 1930)

So, I used the following code:

as.Date("07,29,30", format = "%m,%d,%y")

      

But the year I am returning is 2030, not 1930. How can I tell R to convert the value to a date that is a century earlier?

+3


source to share


4 answers


Since year values ​​between 00 and 68 are encoded as 20 per century. From the documentation strptime

, this appears to be the reason for this.

"Year without century (00-99). Input values ​​00 to 68 prefix to 20 and 69 to 99 to 19 - this is the behavior specified in 2004 and 2008 POSIX, but they also say" Expected in a future version which was referred to by default from a two-digit year, there will be a change. "



You can use the below code to recode it.

d <- as.Date("07,29,30", format = "%m,%d,%y")

> as.Date(ifelse(d > today(), format(d, "19%y-%m-%d"), format(d)))
[1] "1930-07-29"

      

+2


source


I'll put it anyway:



# use this library
library(lubridate)

# convert to the format (your way or you acn use lubridate)
dateconvert <- as.Date("07,29,30", format = "%m,%d,%y") 

# get the year
inputYear <- year(dateconvert)

# convert the year
year(dateconvert) <- ifelse(inputYear > 2000, 1900 + (inputYear %% 100), inputYear)

      

+2


source


To solve this problem use strtotime()

and date()

:

$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));

      

+1


source


Try this: format (as.Date ("07,29,30", format = "% m,% d,% y"), "19% y-% m-% d")

+1


source







All Articles