# [R] Operations with dates just as Month and Day and not Year

Jim Lemon drjimlemon at gmail.com
Sat Jan 24 11:12:23 CET 2015

```Hi Camilo,
If I understand the above, you want to find the minimum number of days
between two day-month dates when there is no information about the
year. I think if you take the difference of the two dates with the
same year and the difference of the dates after subtracting a year
from the "latest" date, the minimum of the two will be the answer you
want.

get_min_date_diff<-function(date1,date2) {
d1<-as.Date(date1,"%m-%d")
d2<-as.Date(date2,"%m-%d")
if(d2 > d1) {
d3<-
as.Date(paste(date2,as.numeric(format(d2,"%Y"))-1,sep="-"),"%m-%d-%Y")
dd1<-d2 - d1
dd2<-d1 - d3
}
else {
d3<-
as.Date(paste(date1,as.numeric(format(d1,"%Y"))-1,sep="-"),"%m-%d-%Y")
dd1<-d1 - d2
dd2<-d2 - d3
}
return(min(c(dd1,dd2)))
}

Kind of complicated, and assumes the "%m-%d" format, but it may be
what you want.

Jim

On Sat, Jan 24, 2015 at 4:21 PM, Camilo Mora <cmora at dal.ca> wrote:
> Hi everyone,
>
> I am trying to calculate the number of days between any two dates in a year regardless of the year. Specifically, image two dates:
> MonDay1 <-   "01-30"      #January 30
> MonDay2 <-   "12-31"      #December 31
>
> I want the difference of those two dates to be
> MonDay1- MonDay2=30 days   #January is closer to December from the prior year than to the December in the year when January is.
>
> FYI. this calculation is to count the number of days between any given date to the peak of the summer, which in the southern hemisphere can be around December.
>
> Unfortunately, I have not been able to make R recognize a date as just Mon-Day. If I try:
> MonDay1<-as.Date("01-30",format="%m-%d")    # this automatically assigns the current year
> [1] "2015-01-30"
>
> This following code allows to define just Mon-Day but it is recognized as character:
> format(strptime("07-30", format="%j"), format="%m-%d")
>
> Any help will be greatly appreciated,
>
> Thanks,
>
> Camilo
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

```

More information about the R-help mailing list