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