4

I'm trying to convert "07,29,30" into a Date format using as.Date() in R.

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

So I used the following code:

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

But the year that I get returned is 2030, not 1930. How can I tell R to convert the value to the date a century before?

Sotos
  • 51,121
  • 6
  • 32
  • 66

4 Answers4

2

I'll put in anyways:

# 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)
din
  • 692
  • 5
  • 12
2

As year values between 00 and 68 are coded as 20 for century. From strptime documentation, it seems following is the reason for this.

"Year without century (00–99). On input, values 00 to 68 are prefixed by 20 and 69 to 99 by 19 – that is the behaviour specified by the 2004 and 2008 POSIX standards, but they do also say ‘it is expected that in a future version the default century inferred from a 2-digit year will 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"
PKumar
  • 10,971
  • 6
  • 37
  • 52
1

To solve this issue use strtotime() and date():

$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));
Doron Yakovlev Golani
  • 5,188
  • 9
  • 36
  • 60
Nilesh
  • 11
  • 1
1

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

Atmajit
  • 11
  • 1