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