Rely on GDate::dmy and GDate::Julian flags, rather than re-checking the
[platform/upstream/glib.git] / glib / gdate.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19 #include "glib.h"
20
21 #include <time.h>
22 #include <string.h>
23 #include <ctype.h>
24 #include <stdlib.h>
25 #include <locale.h>
26
27 GDate*
28 g_date_new ()
29 {
30   GDate *d = g_new0 (GDate, 1); /* happily, 0 is the invalid flag for everything. */
31   
32   return d;
33 }
34
35 GDate*
36 g_date_new_dmy (GDateDay day, GDateMonth m, GDateYear y)
37 {
38   GDate *d;
39   g_return_val_if_fail (g_date_valid_dmy (day, m, y), NULL);
40   
41   d = g_new (GDate, 1);
42   
43   d->julian = FALSE;
44   d->dmy    = TRUE;
45   
46   d->month = m;
47   d->day   = day;
48   d->year  = y;
49   
50   g_assert (g_date_valid (d));
51   
52   return d;
53 }
54
55 GDate*
56 g_date_new_julian (guint32 j)
57 {
58   GDate *d;
59   g_return_val_if_fail (g_date_valid_julian (j), NULL);
60   
61   d = g_new (GDate, 1);
62   
63   d->julian = TRUE;
64   d->dmy    = FALSE;
65   
66   d->julian_days = j;
67   
68   g_assert (g_date_valid (d));
69   
70   return d;
71 }
72
73 void
74 g_date_free (GDate *d)
75 {
76   g_return_if_fail (d != NULL);
77   
78   g_free (d);
79 }
80
81 gboolean     
82 g_date_valid (GDate       *d)
83 {
84   g_return_val_if_fail (d != NULL, FALSE);
85   
86   return (d->julian || d->dmy);
87 }
88
89 static const guint8 days_in_months[2][13] = 
90 {  /* error, jan feb mar apr may jun jul aug sep oct nov dec */
91   {  0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, 
92   {  0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } /* leap year */
93 };
94
95 static const guint16 days_in_year[2][14] = 
96 {  /* 0, jan feb mar apr may  jun  jul  aug  sep  oct  nov  dec */
97   {  0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, 
98   {  0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
99 };
100
101 gboolean     
102 g_date_valid_month (GDateMonth   m)
103
104   return ( (m > G_DATE_BAD_MONTH) && (m < 13) );
105 }
106
107 gboolean     
108 g_date_valid_year (GDateYear    y)
109 {
110   return ( y > G_DATE_BAD_YEAR );
111 }
112
113 gboolean     
114 g_date_valid_day (GDateDay     d)
115 {
116   return ( (d > G_DATE_BAD_DAY) && (d < 32) );
117 }
118
119 gboolean     
120 g_date_valid_weekday (GDateWeekday w)
121 {
122   return ( (w > G_DATE_BAD_WEEKDAY) && (w < 8) );
123 }
124
125 gboolean     
126 g_date_valid_julian (guint32      j)
127 {
128   return (j > G_DATE_BAD_JULIAN);
129 }
130
131 gboolean     
132 g_date_valid_dmy (GDateDay     d, 
133                   GDateMonth   m, 
134                   GDateYear    y)
135 {
136   return ( (m > G_DATE_BAD_MONTH) &&
137            (m < 13)               && 
138            (d > G_DATE_BAD_DAY)   && 
139            (y > G_DATE_BAD_YEAR)  &&   /* must check before using g_date_is_leap_year */
140            (d <=  (g_date_is_leap_year (y) ? 
141                    days_in_months[1][m] : days_in_months[0][m])) );
142 }
143
144
145 /* "Julian days" just means an absolute number of days, where Day 1 ==
146  *   Jan 1, Year 1
147  */
148 static void
149 g_date_update_julian (GDate *d)
150 {
151   GDateYear year;
152   gint index;
153   
154   g_return_if_fail (d != NULL);
155   g_return_if_fail (d->dmy);
156   g_return_if_fail (!d->julian);
157   g_return_if_fail (g_date_valid_dmy (d->day, d->month, d->year));
158   
159   /* What we actually do is: multiply years * 365 days in the year,
160    *  add the number of years divided by 4, subtract the number of
161    *  years divided by 100 and add the number of years divided by 400,
162    *  which accounts for leap year stuff. Code from Steffen Beyer's
163    *  DateCalc. 
164    */
165   
166   year = d->year - 1; /* we know d->year > 0 since it's valid */
167   
168   d->julian_days = year * 365U;
169   d->julian_days += (year >>= 2); /* divide by 4 and add */
170   d->julian_days -= (year /= 25); /* divides original # years by 100 */
171   d->julian_days += year >> 2;    /* divides by 4, which divides original by 400 */
172   
173   index = g_date_is_leap_year (d->year) ? 1 : 0;
174   
175   d->julian_days += days_in_year[index][d->month] + d->day;
176   
177   g_return_if_fail (g_date_valid_julian (d->julian_days));
178   
179   d->julian = TRUE;
180 }
181
182 static void 
183 g_date_update_dmy (GDate *d)
184 {
185   GDateYear y;
186   GDateMonth m;
187   GDateDay day;
188   
189   guint32 A, B, C, D, E, M;
190   
191   g_return_if_fail (d != NULL);
192   g_return_if_fail (d->julian);
193   g_return_if_fail (!d->dmy);
194   g_return_if_fail (g_date_valid_julian (d->julian_days));
195   
196   /* Formula taken from the Calendar FAQ; the formula was for the
197    *  Julian Period which starts on 1 January 4713 BC, so we add
198    *  1,721,425 to the number of days before doing the formula.
199    *
200    * I'm sure this can be simplified for our 1 January 1 AD period
201    * start, but I can't figure out how to unpack the formula.  
202    */
203   
204   A = d->julian_days + 1721425 + 32045;
205   B = ( 4 *(A + 36524) )/ 146097 - 1;
206   C = A - (146097 * B)/4;
207   D = ( 4 * (C + 365) ) / 1461 - 1;
208   E = C - ((1461*D) / 4);
209   M = (5 * (E - 1) + 2)/153;
210   
211   m = M + 3 - (12*(M/10));
212   day = E - (153*M + 2)/5;
213   y = 100 * B + D - 4800 + (M/10);
214   
215 #ifdef G_ENABLE_DEBUG
216   if (!g_date_valid_dmy (day, m, y)) 
217     {
218       g_warning ("\nOOPS julian: %u  computed dmy: %u %u %u\n", 
219                  d->julian_days, day, m, y);
220     }
221 #endif
222   
223   d->month = m;
224   d->day   = day;
225   d->year  = y;
226   
227   d->dmy = TRUE;
228 }
229
230 GDateWeekday 
231 g_date_weekday (GDate *d)
232 {
233   g_return_val_if_fail (d != NULL, G_DATE_BAD_WEEKDAY);
234   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_WEEKDAY);
235   
236   if (!d->julian) 
237     {
238       g_date_update_julian (d);
239     }
240   g_return_val_if_fail (d->julian, G_DATE_BAD_WEEKDAY);
241   
242   return ((d->julian_days - 1) % 7) + 1;
243 }
244
245 GDateMonth   
246 g_date_month (GDate *d)
247 {
248   g_return_val_if_fail (d != NULL, G_DATE_BAD_MONTH);
249   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_MONTH);
250   
251   if (!d->dmy) 
252     {
253       g_date_update_dmy (d);
254     }
255   g_return_val_if_fail (d->dmy, G_DATE_BAD_MONTH);
256   
257   return d->month;
258 }
259
260 GDateYear    
261 g_date_year (GDate *d)
262 {
263   g_return_val_if_fail (d != NULL, G_DATE_BAD_YEAR);
264   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_YEAR);
265   
266   if (!d->dmy) 
267     {
268       g_date_update_dmy (d);
269     }
270   g_return_val_if_fail (d->dmy, G_DATE_BAD_YEAR);  
271   
272   return d->year;
273 }
274
275 GDateDay     
276 g_date_day (GDate *d)
277 {
278   g_return_val_if_fail (d != NULL, G_DATE_BAD_DAY);
279   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_DAY);
280   
281   if (!d->dmy) 
282     {
283       g_date_update_dmy (d);
284     }
285   g_return_val_if_fail (d->dmy, G_DATE_BAD_DAY);  
286   
287   return d->day;
288 }
289
290 guint32      
291 g_date_julian (GDate *d)
292 {
293   g_return_val_if_fail (d != NULL, G_DATE_BAD_JULIAN);
294   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_JULIAN);
295   
296   if (!d->julian) 
297     {
298       g_date_update_julian (d);
299     }
300   g_return_val_if_fail (d->julian, G_DATE_BAD_JULIAN);  
301   
302   return d->julian_days;
303 }
304
305 guint        
306 g_date_day_of_year (GDate *d)
307 {
308   gint index;
309   
310   g_return_val_if_fail (d != NULL, 0);
311   g_return_val_if_fail (g_date_valid (d), 0);
312   
313   if (!d->dmy) 
314     {
315       g_date_update_dmy (d);
316     }
317   g_return_val_if_fail (d->dmy, 0);  
318   
319   index = g_date_is_leap_year (d->year) ? 1 : 0;
320   
321   return (days_in_year[index][d->month] + d->day);
322 }
323
324 guint        
325 g_date_monday_week_of_year (GDate *d)
326 {
327   GDateWeekday wd;
328   guint day;
329   GDate first;
330   
331   g_return_val_if_fail (d != NULL, 0);
332   g_return_val_if_fail (g_date_valid (d), 0);
333   
334   if (!d->dmy) 
335     {
336       g_date_update_dmy (d);
337     }
338   g_return_val_if_fail (d->dmy, 0);  
339   
340   g_date_clear (&first, 1);
341   
342   g_date_set_dmy (&first, 1, 1, d->year);
343   
344   wd = g_date_weekday (&first) - 1; /* make Monday day 0 */
345   day = g_date_day_of_year (d) - 1;
346   
347   return ((day + wd)/7U + (wd == 0 ? 1 : 0));
348 }
349
350 guint        
351 g_date_sunday_week_of_year (GDate *d)
352 {
353   GDateWeekday wd;
354   guint day;
355   GDate first;
356   
357   g_return_val_if_fail (d != NULL, 0);
358   g_return_val_if_fail (g_date_valid (d), 0);
359   
360   if (!d->dmy) 
361     {
362       g_date_update_dmy (d);
363     }
364   g_return_val_if_fail (d->dmy, 0);  
365   
366   g_date_clear (&first, 1);
367   
368   g_date_set_dmy (&first, 1, 1, d->year);
369   
370   wd = g_date_weekday (&first);
371   if (wd == 7) wd = 0; /* make Sunday day 0 */
372   day = g_date_day_of_year (d) - 1;
373   
374   return ((day + wd)/7U + (wd == 0 ? 1 : 0));
375 }
376
377 void         
378 g_date_clear (GDate       *d, guint ndates)
379 {
380   g_return_if_fail (d != NULL);
381   g_return_if_fail (ndates != 0);
382   
383   memset (d, 0x0, ndates*sizeof (GDate)); 
384 }
385
386 /* These are for the parser, output to the user should use *
387  * g_date_strftime () - this creates more never-freed memory to annoy
388  * all those memory debugger users. :-) 
389  */
390
391 static gchar *long_month_names[13] = 
392
393   "Error", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL 
394 };
395
396 static gchar *short_month_names[13] = 
397 {
398   "Error", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL 
399 };
400
401 /* This tells us if we need to update the parse info */
402 static gchar *current_locale = NULL;
403
404 /* order of these in the current locale */
405 static GDateDMY dmy_order[3] = 
406 {
407    G_DATE_DAY, G_DATE_MONTH, G_DATE_YEAR
408 };
409
410 /* Where to chop two-digit years: i.e., for the 1930 default, numbers
411  * 29 and below are counted as in the year 2000, numbers 30 and above
412  * are counted as in the year 1900.  
413  */
414
415 static GDateYear twodigit_start_year = 1930;
416
417 /* It is impossible to enter a year between 1 AD and 99 AD with this
418  * in effect.  
419  */
420 static gboolean using_twodigit_years = FALSE;
421
422 struct _GDateParseTokens {
423   gint num_ints;
424   gint n[3];
425   guint month;
426 };
427
428 typedef struct _GDateParseTokens GDateParseTokens;
429
430 #define NUM_LEN 10
431
432 static void
433 g_date_fill_parse_tokens (const gchar *str, GDateParseTokens *pt)
434 {
435   gchar num[4][NUM_LEN+1];
436   gint i;
437   const gchar *s;
438   
439   /* We count 4, but store 3; so we can give an error
440    * if there are 4.
441    */
442   num[0][0] = num[1][0] = num[2][0] = num[3][0] = '\0';
443   
444   s = str;
445   pt->num_ints = 0;
446   while (*s && pt->num_ints < 4) 
447     {
448       
449       i = 0;
450       while (*s && isdigit (*s) && i <= NUM_LEN)
451         {
452           num[pt->num_ints][i] = *s;
453           ++s; 
454           ++i;
455         }
456       
457       if (i > 0) 
458         {
459           num[pt->num_ints][i] = '\0';
460           ++(pt->num_ints);
461         }
462       
463       if (*s == '\0') break;
464       
465       ++s;
466     }
467   
468   pt->n[0] = pt->num_ints > 0 ? atoi (num[0]) : 0;
469   pt->n[1] = pt->num_ints > 1 ? atoi (num[1]) : 0;
470   pt->n[2] = pt->num_ints > 2 ? atoi (num[2]) : 0;
471   
472   pt->month = G_DATE_BAD_MONTH;
473   
474   if (pt->num_ints < 3)
475     {
476       gchar lcstr[128];
477       int i = 1;
478       
479       strncpy (lcstr, str, 127);
480       g_strdown (lcstr);
481       
482       while (i < 13)
483         {
484           if (long_month_names[i] != NULL) 
485             {
486               const gchar *found = strstr (lcstr, long_month_names[i]);
487               
488               if (found != NULL)
489                 {
490                   pt->month = i;
491                   return;
492                 }
493             }
494           
495           if (short_month_names[i] != NULL) 
496             {
497               const gchar *found = strstr (lcstr, short_month_names[i]);
498               
499               if (found != NULL)
500                 {
501                   pt->month = i;
502                   return;
503                 }
504             }
505           
506           ++i;
507         }
508     }
509 }
510
511 static void
512 g_date_prepare_to_parse (const gchar *str, GDateParseTokens *pt)
513 {
514   const gchar *locale = setlocale (LC_TIME, NULL);
515   gboolean recompute_localeinfo = FALSE;
516   GDate d;
517   
518   g_return_if_fail (locale != NULL); /* should not happen */
519   
520   g_date_clear (&d, 1);              /* clear for scratch use */
521   
522   if ( (current_locale == NULL) || (strcmp (locale, current_locale) != 0) ) 
523     {
524       recompute_localeinfo = TRUE;  /* Uh, there used to be a reason for the temporary */
525     }
526   
527   if (recompute_localeinfo)
528     {
529       int i = 1;
530       GDateParseTokens testpt;
531       gchar buf[128];
532       
533       g_free (current_locale); /* still works if current_locale == NULL */
534       
535       current_locale = g_strdup (locale);
536       
537       while (i < 13) 
538         {
539           g_date_set_dmy (&d, 1, i, 1);
540           
541           g_return_if_fail (g_date_valid (&d));
542           
543           g_date_strftime (buf, 127, "%b", &d);
544           g_free (short_month_names[i]);
545           g_strdown (buf);
546           short_month_names[i] = g_strdup (buf);
547           
548           
549           
550           g_date_strftime (buf, 127, "%B", &d);
551           g_free (long_month_names[i]);
552           g_strdown (buf);
553           long_month_names[i] = g_strdup (buf);
554           
555           ++i;
556         }
557       
558       /* Determine DMY order */
559       
560       g_date_set_dmy (&d, 4, 7, 1776); /* had to pick a random day */
561       
562       g_date_strftime (buf, 127, "%x", &d);
563       
564       g_date_fill_parse_tokens (buf, &testpt);
565       
566       i = 0;
567       while (i < testpt.num_ints)
568         {
569           switch (testpt.n[i])
570             {
571             case 7:
572               dmy_order[i] = G_DATE_MONTH;
573               break;
574             case 4:
575               dmy_order[i] = G_DATE_DAY;
576               break;
577             case 76:
578               using_twodigit_years = TRUE; /* FALL THRU */
579             case 1776:
580               dmy_order[i] = G_DATE_YEAR;
581               break;
582             default:
583               /* leave it unchanged */
584               break;
585             }
586           ++i;
587         }
588       
589 #ifdef G_ENABLE_DEBUG
590       g_message ("**GDate prepared a new set of locale-specific parse rules.");
591       i = 1;
592       while (i < 13) 
593         {
594           g_message ("  %s   %s", long_month_names[i], short_month_names[i]);
595           ++i;
596         }
597       if (using_twodigit_years)
598         {
599           g_message ("**Using twodigit years with cutoff year: %u", twodigit_start_year);
600         }
601       { 
602         gchar *strings[3];
603         i = 0;
604         while (i < 3)
605           {
606             switch (dmy_order[i])
607               {
608               case G_DATE_MONTH:
609                 strings[i] = "Month";
610                 break;
611               case G_DATE_YEAR:
612                 strings[i] = "Year";
613                 break;
614               case G_DATE_DAY:
615                 strings[i] = "Day";
616                 break;
617               default:
618                 strings[i] = NULL;
619                 break;
620               }
621             ++i;
622           }
623         g_message ("**Order: %s, %s, %s", strings[0], strings[1], strings[2]);
624         g_message ("**Sample date in this locale: `%s'", buf);
625       }
626 #endif
627     }
628   
629   g_date_fill_parse_tokens (str, pt);
630 }
631
632 void         
633 g_date_set_parse (GDate       *d, 
634                   const gchar *str)
635 {
636   GDateParseTokens pt;
637   guint m = G_DATE_BAD_MONTH, day = G_DATE_BAD_DAY, y = G_DATE_BAD_YEAR;
638   
639   g_return_if_fail (d != NULL);
640   
641   /* set invalid */
642   g_date_clear (d, 1);
643   
644   g_date_prepare_to_parse (str, &pt);
645   
646 #ifdef G_ENABLE_DEBUG
647   g_message ("Found %d ints, `%d' `%d' `%d' and written out month %d", 
648              pt.num_ints, pt.n[0], pt.n[1], pt.n[2], pt.month);
649 #endif
650   
651   
652   if (pt.num_ints == 4) return; /* presumably a typo; bail out. */
653   
654   if (pt.num_ints > 1)
655     {
656       int i = 0;
657       int j = 0;
658       
659       g_assert (pt.num_ints < 4); /* i.e., it is 2 or 3 */
660       
661       while (i < pt.num_ints && j < 3) 
662         {
663           switch (dmy_order[j])
664             {
665             case G_DATE_MONTH:
666             {
667               if (pt.num_ints == 2 && pt.month != G_DATE_BAD_MONTH)
668                 {
669                   m = pt.month;
670                   ++j;      /* skip months, but don't skip this number */
671                   continue;
672                 }
673               else 
674                 m = pt.n[i];
675             }
676             break;
677             case G_DATE_DAY:
678             {
679               if (pt.num_ints == 2 && pt.month == G_DATE_BAD_MONTH)
680                 {
681                   day = 1;
682                   ++j;      /* skip days, since we may have month/year */
683                   continue;
684                 }
685               day = pt.n[i];
686             }
687             break;
688             case G_DATE_YEAR:
689             {
690               y  = pt.n[i];
691               
692               if (using_twodigit_years && y < 100)
693                 {
694                   guint two     =  twodigit_start_year % 100;
695                   guint century = (twodigit_start_year / 100) * 100;
696                   
697                   if (y < two)
698                     century += 100;
699                   
700                   y += century;
701                 }
702             }
703             break;
704             default:
705               break;
706             }
707           
708           ++i;
709           ++j;
710         }
711       
712       
713       if (pt.num_ints == 3 && !g_date_valid_dmy (day, m, y))
714         {
715           /* Try YYYY MM DD */
716           y   = pt.n[0];
717           m   = pt.n[1];
718           day = pt.n[2];
719           
720           if (using_twodigit_years && y < 100) 
721             y = G_DATE_BAD_YEAR; /* avoids ambiguity */
722         }
723     }
724   else if (pt.num_ints == 1) 
725     {
726       if (pt.month != G_DATE_BAD_MONTH)
727         {
728           /* Month name and year? */
729           m    = pt.month;
730           day  = 1;
731           y = pt.n[0];
732         }
733       else
734         {
735           /* Try yyyymmdd and yymmdd */
736           
737           m   = (pt.n[0]/100) % 100;
738           day = pt.n[0] % 100;
739           y   = pt.n[0]/10000;
740           
741           /* FIXME move this into a separate function */
742           if (using_twodigit_years && y < 100)
743             {
744               guint two     =  twodigit_start_year % 100;
745               guint century = (twodigit_start_year / 100) * 100;
746               
747               if (y < two)
748                 century += 100;
749               
750               y += century;
751             }
752         }
753     }
754   
755   /* See if we got anything valid out of all this. */
756   /* y < 8000 is to catch 19998 style typos; the library is OK up to 65535 or so */
757   if (y < 8000 && g_date_valid_dmy (day, m, y)) 
758     {
759       d->month = m;
760       d->day   = day;
761       d->year  = y;
762       d->dmy   = TRUE;
763     }
764 #ifdef G_ENABLE_DEBUG
765   else 
766     g_message ("Rejected DMY %u %u %u", day, m, y);
767 #endif
768 }
769
770 void         
771 g_date_set_time (GDate *d,
772                  GTime  time)
773 {
774   time_t t = time;
775   struct tm *tm;
776   
777   g_return_if_fail (d != NULL);
778   
779   tm = localtime (&t);
780   
781   if (tm) 
782     {
783       d->julian = FALSE;
784       
785       d->month = tm->tm_mon + 1;
786       d->day   = tm->tm_mday;
787       d->year  = tm->tm_year + 1900;
788       
789       g_return_if_fail (g_date_valid_dmy (d->day, d->month, d->year));
790       
791       d->dmy    = TRUE;
792     }
793   else 
794     {
795       g_date_clear (d, 1);
796     }
797 }
798
799 void         
800 g_date_set_month (GDate     *d, 
801                   GDateMonth m)
802 {
803   g_return_if_fail (d != NULL);
804   g_return_if_fail (g_date_valid_month (m));
805   
806   d->julian = FALSE;
807   
808   d->month = m;
809   
810   if (g_date_valid_dmy (d->day, d->month, d->year))
811     d->dmy = TRUE;
812   else 
813     d->dmy = FALSE;
814 }
815
816 void         
817 g_date_set_day (GDate     *d, 
818                 GDateDay day)
819 {
820   g_return_if_fail (d != NULL);
821   g_return_if_fail (g_date_valid_day (day));
822   
823   d->julian = FALSE;
824   
825   d->day = day;
826   
827   if (g_date_valid_dmy (d->day, d->month, d->year))
828     d->dmy = TRUE;
829   else 
830     d->dmy = FALSE;
831 }
832
833 void         
834 g_date_set_year (GDate     *d, 
835                  GDateYear  y)
836 {
837   g_return_if_fail (d != NULL);
838   g_return_if_fail (g_date_valid_year (y));
839   
840   d->julian = FALSE;
841   
842   d->year = y;
843   
844   if (g_date_valid_dmy (d->day, d->month, d->year))
845     d->dmy = TRUE;
846   else 
847     d->dmy = FALSE;
848 }
849
850 void         
851 g_date_set_dmy (GDate     *d, 
852                 GDateDay   day, 
853                 GDateMonth m, 
854                 GDateYear  y)
855 {
856   g_return_if_fail (d != NULL);
857   g_return_if_fail (g_date_valid_dmy (day, m, y));
858   
859   d->julian = FALSE;
860   
861   d->month = m;
862   d->day   = day;
863   d->year  = y;
864   
865   d->dmy = TRUE;
866 }
867
868 void         
869 g_date_set_julian (GDate *d, guint32 j)
870 {
871   g_return_if_fail (d != NULL);
872   g_return_if_fail (g_date_valid_julian (j));
873   
874   d->julian_days = j;
875   d->julian = TRUE;
876   d->dmy = FALSE;
877 }
878
879
880 gboolean     
881 g_date_is_first_of_month (GDate *d)
882 {
883   g_return_val_if_fail (d != NULL, FALSE);
884   g_return_val_if_fail (g_date_valid (d), FALSE);
885   
886   if (!d->dmy) 
887     {
888       g_date_update_dmy (d);
889     }
890   g_return_val_if_fail (d->dmy, FALSE);  
891   
892   if (d->day == 1) return TRUE;
893   else return FALSE;
894 }
895
896 gboolean     
897 g_date_is_last_of_month (GDate *d)
898 {
899   gint index;
900   
901   g_return_val_if_fail (d != NULL, FALSE);
902   g_return_val_if_fail (g_date_valid (d), FALSE);
903   
904   if (!d->dmy) 
905     {
906       g_date_update_dmy (d);
907     }
908   g_return_val_if_fail (d->dmy, FALSE);  
909   
910   index = g_date_is_leap_year (d->year) ? 1 : 0;
911   
912   if (d->day == days_in_months[index][d->month]) return TRUE;
913   else return FALSE;
914 }
915
916 void         
917 g_date_add_days (GDate *d, guint ndays)
918 {
919   g_return_if_fail (d != NULL);
920   g_return_if_fail (g_date_valid (d));
921   
922   if (!d->julian)
923     {
924       g_date_update_julian (d);
925     }
926   g_return_if_fail (d->julian);
927   
928   d->julian_days += ndays;
929   d->dmy = FALSE;
930 }
931
932 void         
933 g_date_subtract_days (GDate *d, guint ndays)
934 {
935   g_return_if_fail (d != NULL);
936   g_return_if_fail (g_date_valid (d));
937   
938   if (!d->julian)
939     {
940       g_date_update_julian (d);
941     }
942   g_return_if_fail (d->julian);
943   g_return_if_fail (d->julian_days > ndays);
944   
945   d->julian_days -= ndays;
946   d->dmy = FALSE;
947 }
948
949 void         
950 g_date_add_months (GDate       *d, 
951                    guint        nmonths)
952 {
953   guint years, months;
954   gint index;
955   
956   g_return_if_fail (d != NULL);
957   g_return_if_fail (g_date_valid (d));
958   
959   if (!d->dmy) 
960     {
961       g_date_update_dmy (d);
962     }
963   g_return_if_fail (d->dmy);  
964   
965   nmonths += d->month - 1;
966   
967   years  = nmonths/12;
968   months = nmonths%12;
969   
970   d->month = months + 1;
971   d->year  += years;
972   
973   index = g_date_is_leap_year (d->year) ? 1 : 0;
974   
975   if (d->day > days_in_months[index][d->month])
976     d->day = days_in_months[index][d->month];
977   
978   d->julian = FALSE;
979   
980   g_return_if_fail (g_date_valid (d));
981 }
982
983 void         
984 g_date_subtract_months (GDate       *d, 
985                         guint        nmonths)
986 {
987   guint years, months;
988   gint index;
989   
990   g_return_if_fail (d != NULL);
991   g_return_if_fail (g_date_valid (d));
992   
993   if (!d->dmy) 
994     {
995       g_date_update_dmy (d);
996     }
997   g_return_if_fail (d->dmy);  
998   
999   years  = nmonths/12;
1000   months = nmonths%12;
1001   
1002   g_return_if_fail (d->year > years);
1003   
1004   d->year  -= years;
1005   
1006   if (d->month > months) d->month -= months;
1007   else 
1008     {
1009       months -= d->month;
1010       d->month = 12 - months;
1011       d->year -= 1;
1012     }
1013   
1014   index = g_date_is_leap_year (d->year) ? 1 : 0;
1015   
1016   if (d->day > days_in_months[index][d->month])
1017     d->day = days_in_months[index][d->month];
1018   
1019   d->julian = FALSE;
1020   
1021   g_return_if_fail (g_date_valid (d));
1022 }
1023
1024 void         
1025 g_date_add_years (GDate       *d, 
1026                   guint        nyears)
1027 {
1028   g_return_if_fail (d != NULL);
1029   g_return_if_fail (g_date_valid (d));
1030   
1031   if (!d->dmy) 
1032     {
1033       g_date_update_dmy (d);
1034     }
1035   g_return_if_fail (d->dmy);  
1036   
1037   d->year += nyears;
1038   
1039   if (d->month == 2 && d->day == 29)
1040     {
1041       if (!g_date_is_leap_year (d->year))
1042         {
1043           d->day = 28;
1044         }
1045     }
1046   
1047   d->julian = FALSE;
1048 }
1049
1050 void         
1051 g_date_subtract_years (GDate       *d, 
1052                        guint        nyears)
1053 {
1054   g_return_if_fail (d != NULL);
1055   g_return_if_fail (g_date_valid (d));
1056   
1057   if (!d->dmy) 
1058     {
1059       g_date_update_dmy (d);
1060     }
1061   g_return_if_fail (d->dmy);  
1062   g_return_if_fail (d->year > nyears);
1063   
1064   d->year -= nyears;
1065   
1066   if (d->month == 2 && d->day == 29)
1067     {
1068       if (!g_date_is_leap_year (d->year))
1069         {
1070           d->day = 28;
1071         }
1072     }
1073   
1074   d->julian = FALSE;
1075 }
1076
1077
1078 gboolean     
1079 g_date_is_leap_year (GDateYear  year)
1080 {
1081   g_return_val_if_fail (g_date_valid_year (year), FALSE);
1082   
1083   return ( (((year % 4) == 0) && ((year % 100) != 0)) ||
1084            (year % 400) == 0 );
1085 }
1086
1087 guint8         
1088 g_date_days_in_month (GDateMonth month, 
1089                       GDateYear  year)
1090 {
1091   gint index;
1092   
1093   g_return_val_if_fail (g_date_valid_year (year), 0);
1094   g_return_val_if_fail (g_date_valid_month (month), 0);
1095   
1096   index = g_date_is_leap_year (year) ? 1 : 0;
1097   
1098   return days_in_months[index][month];
1099 }
1100
1101 guint8       
1102 g_date_monday_weeks_in_year (GDateYear  year)
1103 {
1104   GDate d;
1105   
1106   g_return_val_if_fail (g_date_valid_year (year), 0);
1107   
1108   g_date_clear (&d, 1);
1109   g_date_set_dmy (&d, 1, 1, year);
1110   if (g_date_weekday (&d) == G_DATE_MONDAY) return 53;
1111   g_date_set_dmy (&d, 31, 12, year);
1112   if (g_date_weekday (&d) == G_DATE_MONDAY) return 53;
1113   if (g_date_is_leap_year (year)) 
1114     {
1115       g_date_set_dmy (&d, 2, 1, year);
1116       if (g_date_weekday (&d) == G_DATE_MONDAY) return 53;
1117       g_date_set_dmy (&d, 30, 12, year);
1118       if (g_date_weekday (&d) == G_DATE_MONDAY) return 53;
1119     }
1120   return 52;
1121 }
1122
1123 guint8       
1124 g_date_sunday_weeks_in_year (GDateYear  year)
1125 {
1126   GDate d;
1127   
1128   g_return_val_if_fail (g_date_valid_year (year), 0);
1129   
1130   g_date_clear (&d, 1);
1131   g_date_set_dmy (&d, 1, 1, year);
1132   if (g_date_weekday (&d) == G_DATE_SUNDAY) return 53;
1133   g_date_set_dmy (&d, 31, 12, year);
1134   if (g_date_weekday (&d) == G_DATE_SUNDAY) return 53;
1135   if (g_date_is_leap_year (year)) 
1136     {
1137       g_date_set_dmy (&d, 2, 1, year);
1138       if (g_date_weekday (&d) == G_DATE_SUNDAY) return 53;
1139       g_date_set_dmy (&d, 30, 12, year);
1140       if (g_date_weekday (&d) == G_DATE_SUNDAY) return 53;
1141     }
1142   return 52;
1143 }
1144
1145 gint         
1146 g_date_compare (GDate     *lhs, 
1147                 GDate     *rhs)
1148 {
1149   g_return_val_if_fail (lhs != NULL, 0);
1150   g_return_val_if_fail (rhs != NULL, 0);
1151   g_return_val_if_fail (g_date_valid (lhs), 0);
1152   g_return_val_if_fail (g_date_valid (rhs), 0);
1153   
1154   /* Remember the self-comparison case! I think it works right now. */
1155   
1156   while (TRUE)
1157     {
1158       
1159       if (lhs->julian && rhs->julian) 
1160         {
1161           if (lhs->julian_days < rhs->julian_days) return -1;
1162           else if (lhs->julian_days > rhs->julian_days) return 1;
1163           else                                          return 0;
1164         }
1165       else if (lhs->dmy && rhs->dmy) 
1166         {
1167           if (lhs->year < rhs->year)               return -1;
1168           else if (lhs->year > rhs->year)               return 1;
1169           else 
1170             {
1171               if (lhs->month < rhs->month)         return -1;
1172               else if (lhs->month > rhs->month)         return 1;
1173               else 
1174                 {
1175                   if (lhs->day < rhs->day)              return -1;
1176                   else if (lhs->day > rhs->day)              return 1;
1177                   else                                       return 0;
1178                 }
1179               
1180             }
1181           
1182         }
1183       else
1184         {
1185           if (!lhs->julian) g_date_update_julian (lhs);
1186           if (!rhs->julian) g_date_update_julian (rhs);
1187           g_return_val_if_fail (lhs->julian, 0);
1188           g_return_val_if_fail (rhs->julian, 0);
1189         }
1190       
1191     }
1192   return 0; /* warnings */
1193 }
1194
1195
1196 void        
1197 g_date_to_struct_tm (GDate      *d, 
1198                      struct tm   *tm)
1199 {
1200   GDateWeekday day;
1201      
1202   g_return_if_fail (d != NULL);
1203   g_return_if_fail (g_date_valid (d));
1204   g_return_if_fail (tm != NULL);
1205   
1206   if (!d->dmy) 
1207     {
1208       g_date_update_dmy (d);
1209     }
1210   g_return_if_fail (d->dmy);
1211   
1212   /* zero all the irrelevant fields to be sure they're valid */
1213   
1214   /* On Linux and maybe other systems, there are weird non-POSIX
1215    * fields on the end of struct tm that choke strftime if they
1216    * contain garbage.  So we need to 0 the entire struct, not just the
1217    * fields we know to exist. 
1218    */
1219   
1220   memset (tm, 0x0, sizeof (struct tm));
1221   
1222   tm->tm_mday = d->day;
1223   tm->tm_mon  = d->month - 1; /* 0-11 goes in tm */
1224   tm->tm_year = ((int)d->year) - 1900; /* X/Open says tm_year can be negative */
1225   
1226   day = g_date_weekday (d);
1227   if (day == 7) day = 0; /* struct tm wants days since Sunday, so Sunday is 0 */
1228   
1229   tm->tm_wday = (int)day;
1230   
1231   tm->tm_yday = g_date_day_of_year (d) - 1; /* 0 to 365 */
1232   tm->tm_isdst = -1; /* -1 means "information not available" */
1233 }
1234
1235 gsize     
1236 g_date_strftime (gchar       *s, 
1237                  gsize        slen, 
1238                  const gchar *format, 
1239                  GDate       *d)
1240 {
1241   struct tm tm;
1242   gsize retval;
1243   
1244   g_return_val_if_fail (d != NULL, 0);
1245   g_return_val_if_fail (g_date_valid (d), 0);
1246   g_return_val_if_fail (slen > 0, 0); 
1247   g_return_val_if_fail (format != 0, 0);
1248   g_return_val_if_fail (s != 0, 0);
1249   
1250   g_date_to_struct_tm (d, &tm);
1251   
1252   retval = strftime (s, slen, format, &tm);
1253   if (retval == 0)
1254     {
1255       /* If retval == 0, the contents of s are undefined.  We define
1256        *  them. 
1257        */
1258       s[0] = '\0';
1259     }
1260   return retval;
1261 }