Home > Net >  converting dates in R is changing to future dates, not past
converting dates in R is changing to future dates, not past

Time:03-07

I use this:

want=as.Date(date, '%d-%b-%y')

to convert dates like this: 1-JAN-52

Instead of returning '1952-01-01' I am getting '2052-01-01'. Any advice?

CodePudding user response:

Welcome to modern computers, all shaped after the early Unix systems of the 1970s. The start of time, so to speak, is the epoch, aka 1 Jan 1970.

Your problem here, in a nutshell, is the inferior input data. You only supply two years and by a widely followed convention, values less than 70 are taken for the next century. It's all about the epoch.

So you have two choices. You could preprend '19' to the year part and parse via %Y, or you could just take the year value out of the date and reduce it by 100 if need be.

Some example code for the second (and IMHO better) option, makeing 1970 the cutoff date:

> datestr <- "1-Jan-52" 
> d <- as.Date(datestr, '%d-%b-%y')   
> 
> d 
[1] "2052-01-01" 
>                
> if (as.integer(strftime(d, "%Y")) >= 1970) { 
    dp <- as.POSIXlt(d)
    dp$year <- dp$year - 100
    d <- as.Date(dp) 
 }     
> d    
[1] "1952-01-01"
> 

You need to go via POSIXlt to get the components easily.

  • Related