!program diff_date_sample
!  Sample program for calculating date in 'year month day' form
!    2008. 5. 29   by I. Tamagawa
!
!implicit none
!
!  integer :: year1, month1, day1, year2, month2, day2, diffday
!
!  write(*, *) 'yyyy mm dd yyyy mm dd'
!  read(*,*) year1, month1, day1, year2, month2, day2
!  call datedif( year1, month1, day1, year2, month2, day2, diffday )
!
!  write(*,*) diffday, ' from ', year2, month2, day2, 'to', year1, month1, day1
!
!
!end


subroutine datedif( year1, month1, day1, year2, month2, day2, diffday )
!     difference between year1/month1/day1 and year2/month2/day2
!        
  implicit none
  integer :: year1, month1, day1
  integer :: year2, month2, day2
  integer :: diffday             ! diffday =  (y/m/d)1 - (y/m/d)2
  integer :: dayofyear
  integer :: fact, tmp, tmp2, d1, d2
  logical :: leepyear
  integer :: year1a, month1a, day1a
  integer :: year2a, month2a, day2a

  year1a = year1; month1a = month1; day1a = day1
  year2a = year2; month2a = month2; day2a = day2

  if( year1 > year2 ) then
    fact = 1
  else if( year1 < year2 ) then
    fact = -1
  else 
    if( month1 > month2 ) then
      fact = 1
    else if( month1 < month2 ) then
      fact = -1
    else
      if( day1 > day2 ) then
        fact = 1
      else if( day1 < day2 ) then
        fact = -1
      else
        fact = 0
      end if
    end if
  end if


  if( fact == 0 ) then
    diffday = 0
    return
  else if( fact == -1 ) then

    tmp = year1; year1 = year2; year2 = tmp
    tmp = month1; month1 = month2; month2 = tmp
    tmp = day1; day1 = day2; day2 = tmp

  end if

 diffday = 0
 do tmp=year2, year1-1
  if( leepyear(tmp) ) then
   diffday = diffday + 366
  else
   diffday = diffday + 365
  end if
 end do
  


! count 
write(*,*) 'year :::', diffday

   d1 = dayofyear( year1, month1, day1 )
   d2 = dayofyear( year2, month2, day2 )
!      write(*,*) year1, month1, day1, d1
!      write(*,*) year2, month2, day2, d2

   diffday = fact*(diffday + d1 - d2)
  year1 = year1a; month1 = month1a; day1 = day1a
  year2 = year2a; month2 = month2a; day2 = day2a

   return
end



logical function leepyear( year )
 integer :: year

 if( mod(year, 4) > 0 ) then
   leepyear  = .FALSE.
 else if( mod(year, 100) > 0 ) then
   leepyear = .TRUE.
 else if( mod(year, 400) > 0 ) then
   leepyear = .FALSE.
 else
   leepyear = .TRUE.
 end if

return
end

   
integer function dayofyear(year, month, day)
 integer :: year, month, day
 logical :: leepyear
 integer :: i
 integer :: m(12)
  m(1) = 31; m(2) = 28; m(3) = 31; m(4) = 30
  m(5) = 31; m(6) = 30; m(7) = 31; m(8) = 31
  m(9) = 30; m(10) = 31; m(11) = 30; m(12) = 31

 if( leepyear( year) ) then
  m(2) = 29
 end if

 dayofyear = 0

 do i=1, month-1
  dayofyear = dayofyear + m(i)
 end do

 dayofyear = dayofyear + day
 return

end


 


