summaryrefslogtreecommitdiff
path: root/lib/checkargs.c
blob: e1c97bea04caa05c2f0a26cad93ea9a82876d0c9 (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
81
82
83
84
85
/*  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 <stdlib.h>
#include <string.h>

int isDateArgument(char* dateString) {
  
  const int MONTHS[] = {31,0,31,30,31,30,31,31,30,31,30,31};
  int i, day, month, year;
  char buffer[5];
  
  /* 'today' is a valid date */ 
  if (strcmp(dateString, "today") == 0)
    return 1;
  
  /* Numeric dates must be eight characters long */
  if (8 != strlen(dateString))
    return 0;
  
  /* Check that the date is entirely formed of numbers */
  for (i = 0; i < 8; i++) {
    if (dateString[i] < '0' || dateString[i] > '9')
      return 0;
  }
  
  /* Check that the date exists */
  memset(buffer, 0, 5);
  strncpy(buffer, dateString + 6, 2);
  day = atoi(buffer);
  strncpy(buffer, dateString + 4, 2); 
  month = atoi(buffer);
  month -= 1;
  strncpy(buffer, dateString, 4);
  year = atoi(buffer);
  
  /* Validate month */
  if (month < 0 || month > 11)
    return 0;
  
  /* Validating dates is simple when the date does not fall into February */
  if (1 != month) {
    if (day < 1 || day > MONTHS[month])
      return 0;
  } else {
    int feb = 28;
    
    /* Februarys are a bit tougher issue */
    if (0 == year % 4) {
      if (0 == year % 100) {
	if (0 == year % 400) {
	  feb = 29;
	} else {
	  feb = 28;
	}
      } else {
	feb = 29;
      }
    }
    if (day < 1 || day > feb)
      return 0;
  }

  /* Avoid user from using dates before 16000301, since those will result in
     incorrect output */
  if(16000301 > atoi(dateString))
    return 0;
  
  return 1;
}