summaryrefslogtreecommitdiff
path: root/generic/datecalc.c
blob: e637b265d2958a80887699b8c7f858f82303edf4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*  datedif - calculates the difference in days between two dates
 *  Copyright (C) 2000 Micael Widell     contact: xeniac@linux.nu
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <time.h>
#include <stdlib.h>
#include <string.h>


/* Gaus's formula - days since 1.3.1600 (Gregorian calendar) */
int days(register int n, register int m, register int y)
{
  register int cy;
  if((m -= 2) <= 0){
    m += 12; y--;
  }
  y -= 1600; cy = y/100;
  return 365*y+y/4-cy+cy/4+367*m/12+n-31;
}


double dateCalc(char * date1, char * date2){   
  
  /* Declare the needed variables */
  char* date[2];
  struct tm *date_tm[2]; 
  time_t date_time_t[2];
  double dateDifference;
  int isToday[2] = { 0, 0 };
  char buffer[5];
  int day[2], month[2], year[2], i;

  date[0] = date1;
  date[1] = date2;  
  
  /* If any of the arguments are "today", then include today's date in the
     right variables */
  for(i = 0; i < 2; i++){
    if(!strcmp(date[i], "today")){
      time(&date_time_t[i]); 
      date_tm[i] = localtime(&date_time_t[i]);
      day[i] = (*date_tm[i]).tm_mday;
      month[i] = (*date_tm[i]).tm_mon + 1;
      year[i] = (*date_tm[i]).tm_year + 1900;
      isToday[i] = 1;
    }
  }
  
  /* Cut out the year, month and day from 8-digit datestrings */
  for (i = 0; i < 2; i++){
    if(!isToday[i]){
      memset(buffer, 0, 5);
      strncpy(buffer, &date[i][6], 2);
      day[i] = atoi(buffer);
      strncpy(buffer, &date[i][4], 2);
      month[i] = atoi(buffer);
      strncpy(buffer, date[i], 4);
      year[i] = atoi(buffer);       
    }
  }
  
  /* Calculate the difference */
  dateDifference = days(day[1], month[1], year[1]) - days(day[0], month[0], year[0]);
  
  return dateDifference;
}