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