7

If I convert the date 10.10.61 (DD.MM.YY) with as.Date(date, format="%d.%m.%y") for some reason it converts it into 2061-10-10.

Is there an elegant way to correct for this or do I have to do it manually by slicing the string and adding "19" in front?

I've also tried the zoo package which brings up the same (wrong) result.

zx8754
  • 52,746
  • 12
  • 114
  • 209
D. Studer
  • 1,711
  • 1
  • 16
  • 35
  • 3
    The reason is found in `?strptime`: _"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"_ – lukeA Oct 10 '17 at 08:37

4 Answers4

9
x = format(as.Date("10.10.61", "%d.%m.%y"), "19%y-%m-%d")
x = as.Date(x)
x
class(x)
AK88
  • 2,946
  • 2
  • 12
  • 31
5

Note that a single sub will slice the string and prepend the year with 19 so it is not so onerous:

as.Date(sub("(..)$", "19\\1", date), "%d.%m.%Y")
## [1] "1961-10-10"

chron Alternately, the chron package defaults to a cutoff of 30 so it will use 1961 by default:

library(chron)
as.Date(dates(date, format = "d.m.y"))
## [1] "1961-10-10"

In chron the year expansion rule is defined by the "chron.year.expand" option which by default is set to the year.expand function and that function's default cut.off is 30. See this SO post for more info: Add correct century to dates with year provided as "Year without century", %y

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
0

If all your dates in 1900s, then you can use this solution:

library(magrittr)
your_date = '10.10.61'
as.Date(your_date,format="%d.%m.%y") %>% format("19%y%m%d") %>% as.Date("%Y%m%d")
Alex
  • 360
  • 2
  • 10
0

If all your dates are in the past, but some are in the 2000s (such as with birthdates), you can use this solution:

origDates = c('10.10.61','10.10.01')

badDates = as.Date(origDates,'%d.%m.%y')
badDates
## [1] "2061-10-10" "2001-10-10"

goodDates = ifelse(badDates > Sys.Date(),
                   format(badDates,'19%y-%m-%d'),
                   format(badDates,'%Y-%m-%d'))
newDates = as.Date(goodDates)
newDates
## [1] "1961-10-10" "2001-10-10"
Drewby
  • 23
  • 5