home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / bsd_srcs / kerberosIV / kdb_edit / maketime.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-03-07  |  2.1 KB  |  86 lines

  1. /*
  2.  * $Source: /usr/src/kerberosIV/kdb_edit/RCS/maketime.c,v $
  3.  * $Author: raeburn $
  4.  *
  5.  * Copyright 1990 by the Massachusetts Institute of Technology.
  6.  *
  7.  * For copying and distribution information, please see the file
  8.  * <mit-copyright.h>.
  9.  *
  10.  * Convert a struct tm * to a UNIX time.
  11.  */
  12.  
  13. #ifndef    lint
  14. static char rcsid_maketime_c[] =
  15. "$Id: maketime.c,v 4.2 90/01/09 15:54:51 raeburn Exp $";
  16. #endif    lint
  17.  
  18. #include <mit-copyright.h>
  19. #include <sys/time.h>
  20.  
  21. #define daysinyear(y) (((y) % 4) ? 365 : (((y) % 100) ? 366 : (((y) % 400) ? 365 : 366)))
  22.  
  23. #define SECSPERDAY 24*60*60
  24. #define SECSPERHOUR 60*60
  25. #define SECSPERMIN 60
  26.  
  27. static int cumdays[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334,
  28.                  365};
  29.  
  30. static int leapyear[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  31. static int nonleapyear[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  32.  
  33. long
  34. maketime(tp, local)
  35. register struct tm *tp;
  36. int local;
  37. {
  38.     register long retval;
  39.     int foo;
  40.     int *marray;
  41.  
  42.     if (tp->tm_mon < 0 || tp->tm_mon > 11 ||
  43.     tp->tm_hour < 0 || tp->tm_hour > 23 ||
  44.     tp->tm_min < 0 || tp->tm_min > 59 ||
  45.     tp->tm_sec < 0 || tp->tm_sec > 59) /* out of range */
  46.     return 0;
  47.  
  48.     retval = 0;
  49.     if (tp->tm_year < 1900)
  50.     foo = tp->tm_year + 1900;
  51.     else
  52.     foo = tp->tm_year;
  53.  
  54.     if (foo < 1901 || foo > 2038)    /* year is too small/large */
  55.     return 0;
  56.  
  57.     if (daysinyear(foo) == 366) {
  58.     if (tp->tm_mon > 1)
  59.         retval+= SECSPERDAY;    /* add leap day */
  60.     marray = leapyear;
  61.     } else
  62.     marray = nonleapyear;
  63.  
  64.     if (tp->tm_mday < 0 || tp->tm_mday > marray[tp->tm_mon])
  65.     return 0;            /* out of range */
  66.  
  67.     while (--foo >= 1970)
  68.     retval += daysinyear(foo) * SECSPERDAY;
  69.  
  70.     retval += cumdays[tp->tm_mon] * SECSPERDAY;
  71.     retval += (tp->tm_mday-1) * SECSPERDAY;
  72.     retval += tp->tm_hour * SECSPERHOUR + tp->tm_min * SECSPERMIN + tp->tm_sec;
  73.  
  74.     if (local) {
  75.     /* need to use local time, so we retrieve timezone info */
  76.     struct timezone tz;
  77.     struct timeval tv;
  78.     if (gettimeofday(&tv, &tz) < 0) {
  79.         /* some error--give up? */
  80.         return(retval);
  81.     }
  82.     retval += tz.tz_minuteswest * SECSPERMIN;
  83.     }
  84.     return(retval);
  85. }
  86.