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