home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-385-Vol-1of3.iso / s / snip1292.zip / SCALDATE.C < prev    next >
Text File  |  1991-10-01  |  1KB  |  48 lines

  1. /*
  2. ** scalar date routines    --    public domain by Ray Gardner
  3. ** These will work over the range 1/01/01 thru 14699/12/31
  4. */
  5.  
  6. int isleap (unsigned yr)
  7. {
  8.    return yr % 400 == 0 || (yr % 4 == 0 && yr % 100 != 0);
  9. }
  10.  
  11. static unsigned months_to_days (unsigned month)
  12. {
  13.    return (month * 3057 - 3007) / 100;
  14. }
  15.  
  16. static long years_to_days (unsigned yr)
  17. {
  18.    return yr * 365L + yr / 4 - yr / 100 + yr / 400;
  19. }
  20.  
  21. long ymd_to_scalar (unsigned yr, unsigned mo, unsigned day)
  22. {
  23.    long scalar;
  24.    scalar = day + months_to_days(mo);
  25.    if ( mo > 2 )                         /* adjust if past February */
  26.       scalar -= isleap(yr) ? 1 : 2;
  27.    yr--;
  28.    scalar += years_to_days(yr);
  29.    return scalar;
  30. }
  31.  
  32. void scalar_to_ymd (long scalar, unsigned *pyr, unsigned *pmo, unsigned *pday)
  33. {
  34.    unsigned n;                /* compute inverse of years_to_days() */
  35.  
  36.    for ( n = (unsigned)((scalar * 400L) / 146097); years_to_days(n) < scalar;)
  37.       n++;                          /* 146097 == years_to_days(400) */
  38.    *pyr = n;
  39.    n = (unsigned)(scalar - years_to_days(n-1));
  40.    if ( n > 59 ) {                       /* adjust if past February */
  41.       n += 2;
  42.       if ( isleap(*pyr) )
  43.          n -= n > 62 ? 1 : 2;
  44.    }
  45.    *pmo = (n * 100 + 3007) / 3057;  /* inverse of months_to_days() */
  46.    *pday = n - months_to_days(*pmo);
  47. }
  48.