Add a function to calculate the ISO 8601 week number of a date. (#92579,
[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 /**
398  * g_date_get_iso8601_week_of_year:
399  * @date: a valid #GDate
400  *
401  * Returns the week of the year, where weeks are interpreted according
402  * to ISO 8601. 
403  * 
404  * Returns: ISO 8601 week number of the year.
405  *
406  * Since: 2.6
407  **/
408 guint
409 g_date_get_iso8601_week_of_year (const GDate *d)
410 {
411   guint j, d4, L, d1, w;
412
413   g_return_val_if_fail (d != NULL, 0);
414   g_return_val_if_fail (g_date_valid (d), 0);
415   
416   if (!d->julian)
417     g_date_update_julian (d);
418   g_return_val_if_fail (d->julian, 0);
419
420   /* Formula taken from the Calendar FAQ; the formula was for the
421    * Julian Period which starts on 1 January 4713 BC, so we add
422    * 1,721,425 to the number of days before doing the formula. 
423    */
424   j  = d->julian + 1721425;
425   d4 = (j + 31741 - (j % 7)) % 146097 % 36524 % 1461;
426   L  = d4 / 1460;
427   d1 = ((d4 - L) % 365) + L;
428   w  = d1 / 7 + 1;
429
430   return w;
431 }
432
433 gint
434 g_date_days_between (const GDate *d1,
435                      const GDate *d2)
436 {
437   g_return_val_if_fail (d1 != NULL, 0);
438   g_return_val_if_fail (d2 != NULL, 0);
439
440   g_return_val_if_fail (g_date_valid (d1), 0);
441   g_return_val_if_fail (g_date_valid (d2), 0);
442
443   return (gint)g_date_get_julian (d2) - (gint)g_date_get_julian (d1);
444 }
445
446 void         
447 g_date_clear (GDate       *d, guint ndates)
448 {
449   g_return_if_fail (d != NULL);
450   g_return_if_fail (ndates != 0);
451   
452   memset (d, 0x0, ndates*sizeof (GDate)); 
453 }
454
455 G_LOCK_DEFINE_STATIC (g_date_global);
456
457 /* These are for the parser, output to the user should use *
458  * g_date_strftime () - this creates more never-freed memory to annoy
459  * all those memory debugger users. :-) 
460  */
461
462 static gchar *long_month_names[13] = 
463
464   "Error", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL 
465 };
466
467 static gchar *short_month_names[13] = 
468 {
469   "Error", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL 
470 };
471
472 /* This tells us if we need to update the parse info */
473 static gchar *current_locale = NULL;
474
475 /* order of these in the current locale */
476 static GDateDMY dmy_order[3] = 
477 {
478    G_DATE_DAY, G_DATE_MONTH, G_DATE_YEAR
479 };
480
481 /* Where to chop two-digit years: i.e., for the 1930 default, numbers
482  * 29 and below are counted as in the year 2000, numbers 30 and above
483  * are counted as in the year 1900.  
484  */
485
486 static GDateYear twodigit_start_year = 1930;
487
488 /* It is impossible to enter a year between 1 AD and 99 AD with this
489  * in effect.  
490  */
491 static gboolean using_twodigit_years = FALSE;
492
493 /* Adjustment of locale era to AD, non-zero means using locale era
494  */
495 static gint locale_era_adjust = 0;
496
497 struct _GDateParseTokens {
498   gint num_ints;
499   gint n[3];
500   guint month;
501 };
502
503 typedef struct _GDateParseTokens GDateParseTokens;
504
505 #define NUM_LEN 10
506
507 /* HOLDS: g_date_global_lock */
508 static void
509 g_date_fill_parse_tokens (const gchar *str, GDateParseTokens *pt)
510 {
511   gchar num[4][NUM_LEN+1];
512   gint i;
513   const guchar *s;
514   
515   /* We count 4, but store 3; so we can give an error
516    * if there are 4.
517    */
518   num[0][0] = num[1][0] = num[2][0] = num[3][0] = '\0';
519   
520   s = (const guchar *) str;
521   pt->num_ints = 0;
522   while (*s && pt->num_ints < 4) 
523     {
524       
525       i = 0;
526       while (*s && g_ascii_isdigit (*s) && i <= NUM_LEN)
527         {
528           num[pt->num_ints][i] = *s;
529           ++s; 
530           ++i;
531         }
532       
533       if (i > 0) 
534         {
535           num[pt->num_ints][i] = '\0';
536           ++(pt->num_ints);
537         }
538       
539       if (*s == '\0') break;
540       
541       ++s;
542     }
543   
544   pt->n[0] = pt->num_ints > 0 ? atoi (num[0]) : 0;
545   pt->n[1] = pt->num_ints > 1 ? atoi (num[1]) : 0;
546   pt->n[2] = pt->num_ints > 2 ? atoi (num[2]) : 0;
547   
548   pt->month = G_DATE_BAD_MONTH;
549   
550   if (pt->num_ints < 3)
551     {
552       gchar *casefold;
553       gchar *normalized;
554       
555       casefold = g_utf8_casefold (str, -1);
556       normalized = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
557       g_free (casefold);
558
559       i = 1;
560       while (i < 13)
561         {
562           if (long_month_names[i] != NULL) 
563             {
564               const gchar *found = strstr (normalized, long_month_names[i]);
565               
566               if (found != NULL)
567                 {
568                   pt->month = i;
569                   break;
570                 }
571             }
572           
573           if (short_month_names[i] != NULL) 
574             {
575               const gchar *found = strstr (normalized, short_month_names[i]);
576               
577               if (found != NULL)
578                 {
579                   pt->month = i;
580                   break;
581                 }
582             }
583
584           ++i;
585         }
586
587       g_free (normalized);
588     }
589 }
590
591 /* HOLDS: g_date_global_lock */
592 static void
593 g_date_prepare_to_parse (const gchar *str, GDateParseTokens *pt)
594 {
595   const gchar *locale = setlocale (LC_TIME, NULL);
596   gboolean recompute_localeinfo = FALSE;
597   GDate d;
598   
599   g_return_if_fail (locale != NULL); /* should not happen */
600   
601   g_date_clear (&d, 1);              /* clear for scratch use */
602   
603   if ( (current_locale == NULL) || (strcmp (locale, current_locale) != 0) ) 
604     {
605       recompute_localeinfo = TRUE;  /* Uh, there used to be a reason for the temporary */
606     }
607   
608   if (recompute_localeinfo)
609     {
610       int i = 1;
611       GDateParseTokens testpt;
612       gchar buf[128];
613       
614       g_free (current_locale); /* still works if current_locale == NULL */
615       
616       current_locale = g_strdup (locale);
617       
618       while (i < 13) 
619         {
620           gchar *casefold;
621           
622           g_date_set_dmy (&d, 1, i, 1);
623           
624           g_return_if_fail (g_date_valid (&d));
625           
626           g_date_strftime (buf, 127, "%b", &d);
627
628           casefold = g_utf8_casefold (buf, -1);
629           g_free (short_month_names[i]);
630           short_month_names[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
631           g_free (casefold);
632           
633           g_date_strftime (buf, 127, "%B", &d);
634           casefold = g_utf8_casefold (buf, -1);
635           g_free (long_month_names[i]);
636           long_month_names[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
637           g_free (casefold);
638           
639           ++i;
640         }
641       
642       /* Determine DMY order */
643       
644       /* had to pick a random day - don't change this, some strftimes
645        * are broken on some days, and this one is good so far. */
646       g_date_set_dmy (&d, 4, 7, 1976);
647       
648       g_date_strftime (buf, 127, "%x", &d);
649       
650       g_date_fill_parse_tokens (buf, &testpt);
651       
652       i = 0;
653       while (i < testpt.num_ints)
654         {
655           switch (testpt.n[i])
656             {
657             case 7:
658               dmy_order[i] = G_DATE_MONTH;
659               break;
660             case 4:
661               dmy_order[i] = G_DATE_DAY;
662               break;
663             case 76:
664               using_twodigit_years = TRUE; /* FALL THRU */
665             case 1976:
666               dmy_order[i] = G_DATE_YEAR;
667               break;
668             default:
669               /* assume locale era */
670               locale_era_adjust = 1976 - testpt.n[i];
671               dmy_order[i] = G_DATE_YEAR;
672               break;
673             }
674           ++i;
675         }
676       
677 #ifdef G_ENABLE_DEBUG
678       DEBUG_MSG (("**GDate prepared a new set of locale-specific parse rules."));
679       i = 1;
680       while (i < 13) 
681         {
682           DEBUG_MSG (("  %s   %s", long_month_names[i], short_month_names[i]));
683           ++i;
684         }
685       if (using_twodigit_years)
686         DEBUG_MSG (("**Using twodigit years with cutoff year: %u", twodigit_start_year));
687       { 
688         gchar *strings[3];
689         i = 0;
690         while (i < 3)
691           {
692             switch (dmy_order[i])
693               {
694               case G_DATE_MONTH:
695                 strings[i] = "Month";
696                 break;
697               case G_DATE_YEAR:
698                 strings[i] = "Year";
699                 break;
700               case G_DATE_DAY:
701                 strings[i] = "Day";
702                 break;
703               default:
704                 strings[i] = NULL;
705                 break;
706               }
707             ++i;
708           }
709         DEBUG_MSG (("**Order: %s, %s, %s", strings[0], strings[1], strings[2]));
710         DEBUG_MSG (("**Sample date in this locale: `%s'", buf));
711       }
712 #endif
713     }
714   
715   g_date_fill_parse_tokens (str, pt);
716 }
717
718 void         
719 g_date_set_parse (GDate       *d, 
720                   const gchar *str)
721 {
722   GDateParseTokens pt;
723   guint m = G_DATE_BAD_MONTH, day = G_DATE_BAD_DAY, y = G_DATE_BAD_YEAR;
724   
725   g_return_if_fail (d != NULL);
726   
727   /* set invalid */
728   g_date_clear (d, 1);
729   
730   G_LOCK (g_date_global);
731
732   g_date_prepare_to_parse (str, &pt);
733   
734   DEBUG_MSG (("Found %d ints, `%d' `%d' `%d' and written out month %d", 
735               pt.num_ints, pt.n[0], pt.n[1], pt.n[2], pt.month));
736   
737   
738   if (pt.num_ints == 4) 
739     {
740       G_UNLOCK (g_date_global);
741       return; /* presumably a typo; bail out. */
742     }
743   
744   if (pt.num_ints > 1)
745     {
746       int i = 0;
747       int j = 0;
748       
749       g_assert (pt.num_ints < 4); /* i.e., it is 2 or 3 */
750       
751       while (i < pt.num_ints && j < 3) 
752         {
753           switch (dmy_order[j])
754             {
755             case G_DATE_MONTH:
756             {
757               if (pt.num_ints == 2 && pt.month != G_DATE_BAD_MONTH)
758                 {
759                   m = pt.month;
760                   ++j;      /* skip months, but don't skip this number */
761                   continue;
762                 }
763               else 
764                 m = pt.n[i];
765             }
766             break;
767             case G_DATE_DAY:
768             {
769               if (pt.num_ints == 2 && pt.month == G_DATE_BAD_MONTH)
770                 {
771                   day = 1;
772                   ++j;      /* skip days, since we may have month/year */
773                   continue;
774                 }
775               day = pt.n[i];
776             }
777             break;
778             case G_DATE_YEAR:
779             {
780               y  = pt.n[i];
781               
782               if (locale_era_adjust != 0)
783                 {
784                   y += locale_era_adjust;
785                 }
786               else if (using_twodigit_years && y < 100)
787                 {
788                   guint two     =  twodigit_start_year % 100;
789                   guint century = (twodigit_start_year / 100) * 100;
790                   
791                   if (y < two)
792                     century += 100;
793                   
794                   y += century;
795                 }
796             }
797             break;
798             default:
799               break;
800             }
801           
802           ++i;
803           ++j;
804         }
805       
806       
807       if (pt.num_ints == 3 && !g_date_valid_dmy (day, m, y))
808         {
809           /* Try YYYY MM DD */
810           y   = pt.n[0];
811           m   = pt.n[1];
812           day = pt.n[2];
813           
814           if (using_twodigit_years && y < 100) 
815             y = G_DATE_BAD_YEAR; /* avoids ambiguity */
816         }
817       else if (pt.num_ints == 2)
818         {
819           if (m == G_DATE_BAD_MONTH && pt.month != G_DATE_BAD_MONTH)
820             {
821               m = pt.month;
822             }
823         }
824     }
825   else if (pt.num_ints == 1) 
826     {
827       if (pt.month != G_DATE_BAD_MONTH)
828         {
829           /* Month name and year? */
830           m    = pt.month;
831           day  = 1;
832           y = pt.n[0];
833         }
834       else
835         {
836           /* Try yyyymmdd and yymmdd */
837           
838           m   = (pt.n[0]/100) % 100;
839           day = pt.n[0] % 100;
840           y   = pt.n[0]/10000;
841           
842           /* FIXME move this into a separate function */
843           if (using_twodigit_years && y < 100)
844             {
845               guint two     =  twodigit_start_year % 100;
846               guint century = (twodigit_start_year / 100) * 100;
847               
848               if (y < two)
849                 century += 100;
850               
851               y += century;
852             }
853         }
854     }
855   
856   /* See if we got anything valid out of all this. */
857   /* y < 8000 is to catch 19998 style typos; the library is OK up to 65535 or so */
858   if (y < 8000 && g_date_valid_dmy (day, m, y)) 
859     {
860       d->month = m;
861       d->day   = day;
862       d->year  = y;
863       d->dmy   = TRUE;
864     }
865 #ifdef G_ENABLE_DEBUG
866   else 
867     DEBUG_MSG (("Rejected DMY %u %u %u", day, m, y));
868 #endif
869   G_UNLOCK (g_date_global);
870 }
871
872 void         
873 g_date_set_time (GDate *d,
874                  GTime  time)
875 {
876   time_t t = time;
877   struct tm tm;
878   
879   g_return_if_fail (d != NULL);
880   
881 #ifdef HAVE_LOCALTIME_R
882   localtime_r (&t, &tm);
883 #else
884   {
885     struct tm *ptm = localtime (&t);
886     g_assert (ptm);
887     memcpy ((void *) &tm, (void *) ptm, sizeof(struct tm));
888   }
889 #endif
890   
891   d->julian = FALSE;
892   
893   d->month = tm.tm_mon + 1;
894   d->day   = tm.tm_mday;
895   d->year  = tm.tm_year + 1900;
896   
897   g_return_if_fail (g_date_valid_dmy (d->day, d->month, d->year));
898   
899   d->dmy    = TRUE;
900 }
901
902 void         
903 g_date_set_month (GDate     *d, 
904                   GDateMonth m)
905 {
906   g_return_if_fail (d != NULL);
907   g_return_if_fail (g_date_valid_month (m));
908
909   if (d->julian && !d->dmy) g_date_update_dmy(d);
910   d->julian = FALSE;
911   
912   d->month = m;
913   
914   if (g_date_valid_dmy (d->day, d->month, d->year))
915     d->dmy = TRUE;
916   else 
917     d->dmy = FALSE;
918 }
919
920 void         
921 g_date_set_day (GDate     *d, 
922                 GDateDay day)
923 {
924   g_return_if_fail (d != NULL);
925   g_return_if_fail (g_date_valid_day (day));
926   
927   if (d->julian && !d->dmy) g_date_update_dmy(d);
928   d->julian = FALSE;
929   
930   d->day = day;
931   
932   if (g_date_valid_dmy (d->day, d->month, d->year))
933     d->dmy = TRUE;
934   else 
935     d->dmy = FALSE;
936 }
937
938 void         
939 g_date_set_year (GDate     *d, 
940                  GDateYear  y)
941 {
942   g_return_if_fail (d != NULL);
943   g_return_if_fail (g_date_valid_year (y));
944   
945   if (d->julian && !d->dmy) g_date_update_dmy(d);
946   d->julian = FALSE;
947   
948   d->year = y;
949   
950   if (g_date_valid_dmy (d->day, d->month, d->year))
951     d->dmy = TRUE;
952   else 
953     d->dmy = FALSE;
954 }
955
956 void         
957 g_date_set_dmy (GDate     *d, 
958                 GDateDay   day, 
959                 GDateMonth m, 
960                 GDateYear  y)
961 {
962   g_return_if_fail (d != NULL);
963   g_return_if_fail (g_date_valid_dmy (day, m, y));
964   
965   d->julian = FALSE;
966   
967   d->month = m;
968   d->day   = day;
969   d->year  = y;
970   
971   d->dmy = TRUE;
972 }
973
974 void         
975 g_date_set_julian (GDate *d, guint32 j)
976 {
977   g_return_if_fail (d != NULL);
978   g_return_if_fail (g_date_valid_julian (j));
979   
980   d->julian_days = j;
981   d->julian = TRUE;
982   d->dmy = FALSE;
983 }
984
985
986 gboolean     
987 g_date_is_first_of_month (const GDate *d)
988 {
989   g_return_val_if_fail (d != NULL, FALSE);
990   g_return_val_if_fail (g_date_valid (d), FALSE);
991   
992   if (!d->dmy) 
993     {
994       g_date_update_dmy (d);
995     }
996   g_return_val_if_fail (d->dmy, FALSE);  
997   
998   if (d->day == 1) return TRUE;
999   else return FALSE;
1000 }
1001
1002 gboolean     
1003 g_date_is_last_of_month (const GDate *d)
1004 {
1005   gint index;
1006   
1007   g_return_val_if_fail (d != NULL, FALSE);
1008   g_return_val_if_fail (g_date_valid (d), FALSE);
1009   
1010   if (!d->dmy) 
1011     {
1012       g_date_update_dmy (d);
1013     }
1014   g_return_val_if_fail (d->dmy, FALSE);  
1015   
1016   index = g_date_is_leap_year (d->year) ? 1 : 0;
1017   
1018   if (d->day == days_in_months[index][d->month]) return TRUE;
1019   else return FALSE;
1020 }
1021
1022 void         
1023 g_date_add_days (GDate *d, guint ndays)
1024 {
1025   g_return_if_fail (d != NULL);
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 (d != NULL);
1042   g_return_if_fail (g_date_valid (d));
1043   
1044   if (!d->julian)
1045     {
1046       g_date_update_julian (d);
1047     }
1048   g_return_if_fail (d->julian);
1049   g_return_if_fail (d->julian_days > ndays);
1050   
1051   d->julian_days -= ndays;
1052   d->dmy = FALSE;
1053 }
1054
1055 void         
1056 g_date_add_months (GDate       *d, 
1057                    guint        nmonths)
1058 {
1059   guint years, months;
1060   gint index;
1061   
1062   g_return_if_fail (d != NULL);
1063   g_return_if_fail (g_date_valid (d));
1064   
1065   if (!d->dmy) 
1066     {
1067       g_date_update_dmy (d);
1068     }
1069   g_return_if_fail (d->dmy);  
1070   
1071   nmonths += d->month - 1;
1072   
1073   years  = nmonths/12;
1074   months = nmonths%12;
1075   
1076   d->month = months + 1;
1077   d->year  += years;
1078   
1079   index = g_date_is_leap_year (d->year) ? 1 : 0;
1080   
1081   if (d->day > days_in_months[index][d->month])
1082     d->day = days_in_months[index][d->month];
1083   
1084   d->julian = FALSE;
1085   
1086   g_return_if_fail (g_date_valid (d));
1087 }
1088
1089 void         
1090 g_date_subtract_months (GDate       *d, 
1091                         guint        nmonths)
1092 {
1093   guint years, months;
1094   gint index;
1095   
1096   g_return_if_fail (d != NULL);
1097   g_return_if_fail (g_date_valid (d));
1098   
1099   if (!d->dmy) 
1100     {
1101       g_date_update_dmy (d);
1102     }
1103   g_return_if_fail (d->dmy);  
1104   
1105   years  = nmonths/12;
1106   months = nmonths%12;
1107   
1108   g_return_if_fail (d->year > years);
1109   
1110   d->year  -= years;
1111   
1112   if (d->month > months) d->month -= months;
1113   else 
1114     {
1115       months -= d->month;
1116       d->month = 12 - months;
1117       d->year -= 1;
1118     }
1119   
1120   index = g_date_is_leap_year (d->year) ? 1 : 0;
1121   
1122   if (d->day > days_in_months[index][d->month])
1123     d->day = days_in_months[index][d->month];
1124   
1125   d->julian = FALSE;
1126   
1127   g_return_if_fail (g_date_valid (d));
1128 }
1129
1130 void         
1131 g_date_add_years (GDate       *d, 
1132                   guint        nyears)
1133 {
1134   g_return_if_fail (d != NULL);
1135   g_return_if_fail (g_date_valid (d));
1136   
1137   if (!d->dmy) 
1138     {
1139       g_date_update_dmy (d);
1140     }
1141   g_return_if_fail (d->dmy);  
1142   
1143   d->year += nyears;
1144   
1145   if (d->month == 2 && d->day == 29)
1146     {
1147       if (!g_date_is_leap_year (d->year))
1148         {
1149           d->day = 28;
1150         }
1151     }
1152   
1153   d->julian = FALSE;
1154 }
1155
1156 void         
1157 g_date_subtract_years (GDate       *d, 
1158                        guint        nyears)
1159 {
1160   g_return_if_fail (d != NULL);
1161   g_return_if_fail (g_date_valid (d));
1162   
1163   if (!d->dmy) 
1164     {
1165       g_date_update_dmy (d);
1166     }
1167   g_return_if_fail (d->dmy);  
1168   g_return_if_fail (d->year > nyears);
1169   
1170   d->year -= nyears;
1171   
1172   if (d->month == 2 && d->day == 29)
1173     {
1174       if (!g_date_is_leap_year (d->year))
1175         {
1176           d->day = 28;
1177         }
1178     }
1179   
1180   d->julian = FALSE;
1181 }
1182
1183
1184 gboolean     
1185 g_date_is_leap_year (GDateYear  year)
1186 {
1187   g_return_val_if_fail (g_date_valid_year (year), FALSE);
1188   
1189   return ( (((year % 4) == 0) && ((year % 100) != 0)) ||
1190            (year % 400) == 0 );
1191 }
1192
1193 guint8         
1194 g_date_get_days_in_month (GDateMonth month, 
1195                           GDateYear  year)
1196 {
1197   gint index;
1198   
1199   g_return_val_if_fail (g_date_valid_year (year), 0);
1200   g_return_val_if_fail (g_date_valid_month (month), 0);
1201   
1202   index = g_date_is_leap_year (year) ? 1 : 0;
1203   
1204   return days_in_months[index][month];
1205 }
1206
1207 guint8       
1208 g_date_get_monday_weeks_in_year (GDateYear  year)
1209 {
1210   GDate d;
1211   
1212   g_return_val_if_fail (g_date_valid_year (year), 0);
1213   
1214   g_date_clear (&d, 1);
1215   g_date_set_dmy (&d, 1, 1, year);
1216   if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1217   g_date_set_dmy (&d, 31, 12, year);
1218   if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1219   if (g_date_is_leap_year (year)) 
1220     {
1221       g_date_set_dmy (&d, 2, 1, year);
1222       if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1223       g_date_set_dmy (&d, 30, 12, year);
1224       if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1225     }
1226   return 52;
1227 }
1228
1229 guint8       
1230 g_date_get_sunday_weeks_in_year (GDateYear  year)
1231 {
1232   GDate d;
1233   
1234   g_return_val_if_fail (g_date_valid_year (year), 0);
1235   
1236   g_date_clear (&d, 1);
1237   g_date_set_dmy (&d, 1, 1, year);
1238   if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1239   g_date_set_dmy (&d, 31, 12, year);
1240   if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1241   if (g_date_is_leap_year (year)) 
1242     {
1243       g_date_set_dmy (&d, 2, 1, year);
1244       if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1245       g_date_set_dmy (&d, 30, 12, year);
1246       if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1247     }
1248   return 52;
1249 }
1250
1251 gint         
1252 g_date_compare (const GDate *lhs, 
1253                 const GDate *rhs)
1254 {
1255   g_return_val_if_fail (lhs != NULL, 0);
1256   g_return_val_if_fail (rhs != NULL, 0);
1257   g_return_val_if_fail (g_date_valid (lhs), 0);
1258   g_return_val_if_fail (g_date_valid (rhs), 0);
1259   
1260   /* Remember the self-comparison case! I think it works right now. */
1261   
1262   while (TRUE)
1263     {
1264       
1265       if (lhs->julian && rhs->julian) 
1266         {
1267           if (lhs->julian_days < rhs->julian_days) return -1;
1268           else if (lhs->julian_days > rhs->julian_days) return 1;
1269           else                                          return 0;
1270         }
1271       else if (lhs->dmy && rhs->dmy) 
1272         {
1273           if (lhs->year < rhs->year)               return -1;
1274           else if (lhs->year > rhs->year)               return 1;
1275           else 
1276             {
1277               if (lhs->month < rhs->month)         return -1;
1278               else if (lhs->month > rhs->month)         return 1;
1279               else 
1280                 {
1281                   if (lhs->day < rhs->day)              return -1;
1282                   else if (lhs->day > rhs->day)              return 1;
1283                   else                                       return 0;
1284                 }
1285               
1286             }
1287           
1288         }
1289       else
1290         {
1291           if (!lhs->julian) g_date_update_julian (lhs);
1292           if (!rhs->julian) g_date_update_julian (rhs);
1293           g_return_val_if_fail (lhs->julian, 0);
1294           g_return_val_if_fail (rhs->julian, 0);
1295         }
1296       
1297     }
1298   return 0; /* warnings */
1299 }
1300
1301
1302 void        
1303 g_date_to_struct_tm (const GDate *d, 
1304                      struct tm   *tm)
1305 {
1306   GDateWeekday day;
1307      
1308   g_return_if_fail (d != NULL);
1309   g_return_if_fail (g_date_valid (d));
1310   g_return_if_fail (tm != NULL);
1311   
1312   if (!d->dmy) 
1313     {
1314       g_date_update_dmy (d);
1315     }
1316   g_return_if_fail (d->dmy);
1317   
1318   /* zero all the irrelevant fields to be sure they're valid */
1319   
1320   /* On Linux and maybe other systems, there are weird non-POSIX
1321    * fields on the end of struct tm that choke strftime if they
1322    * contain garbage.  So we need to 0 the entire struct, not just the
1323    * fields we know to exist. 
1324    */
1325   
1326   memset (tm, 0x0, sizeof (struct tm));
1327   
1328   tm->tm_mday = d->day;
1329   tm->tm_mon  = d->month - 1; /* 0-11 goes in tm */
1330   tm->tm_year = ((int)d->year) - 1900; /* X/Open says tm_year can be negative */
1331   
1332   day = g_date_get_weekday (d);
1333   if (day == 7) day = 0; /* struct tm wants days since Sunday, so Sunday is 0 */
1334   
1335   tm->tm_wday = (int)day;
1336   
1337   tm->tm_yday = g_date_get_day_of_year (d) - 1; /* 0 to 365 */
1338   tm->tm_isdst = -1; /* -1 means "information not available" */
1339 }
1340
1341 void
1342 g_date_clamp (GDate *date,
1343               const GDate *min_date,
1344               const GDate *max_date)
1345 {
1346   g_return_if_fail (date);
1347   g_return_if_fail (g_date_valid (date));
1348   if (min_date != NULL)
1349     g_return_if_fail (g_date_valid (min_date));
1350   if (max_date != NULL)
1351     g_return_if_fail (g_date_valid (max_date));
1352   if (min_date != NULL && max_date != NULL)
1353     g_return_if_fail (g_date_compare (min_date, max_date) <= 0);
1354
1355   if (min_date && g_date_compare (date, min_date) < 0)
1356     *date = *min_date;
1357
1358   if (max_date && g_date_compare (max_date, date) < 0)
1359     *date = *max_date;
1360 }
1361
1362 void
1363 g_date_order (GDate *date1,
1364               GDate *date2)
1365 {
1366   g_return_if_fail (date1 != NULL);
1367   g_return_if_fail (date2 != NULL);
1368   g_return_if_fail (g_date_valid (date1));
1369   g_return_if_fail (g_date_valid (date2));
1370
1371   if (g_date_compare (date1, date2) > 0)
1372     {
1373       GDate tmp = *date1;
1374       *date1 = *date2;
1375       *date2 = tmp;
1376     }
1377 }
1378
1379 gsize     
1380 g_date_strftime (gchar       *s, 
1381                  gsize        slen, 
1382                  const gchar *format, 
1383                  const GDate *d)
1384 {
1385   struct tm tm;
1386   gsize locale_format_len = 0;
1387   gchar *locale_format;
1388   gsize tmplen;
1389   gchar *tmpbuf;
1390   gsize tmpbufsize;
1391   gsize convlen = 0;
1392   gchar *convbuf;
1393   GError *error = NULL;
1394   gsize retval;
1395
1396   g_return_val_if_fail (d != NULL, 0);
1397   g_return_val_if_fail (g_date_valid (d), 0);
1398   g_return_val_if_fail (slen > 0, 0); 
1399   g_return_val_if_fail (format != 0, 0);
1400   g_return_val_if_fail (s != 0, 0);
1401
1402   g_date_to_struct_tm (d, &tm);
1403
1404   locale_format = g_locale_from_utf8 (format, -1, NULL, &locale_format_len, &error);
1405
1406   if (error)
1407     {
1408       g_warning (G_STRLOC "Error converting format to locale encoding: %s\n", error->message);
1409       g_error_free (error);
1410
1411       s[0] = '\0';
1412       return 0;
1413     }
1414
1415   tmpbufsize = MAX (128, locale_format_len * 2);
1416   while (TRUE)
1417     {
1418       tmpbuf = g_malloc (tmpbufsize);
1419
1420       /* Set the first byte to something other than '\0', to be able to
1421        * recognize whether strftime actually failed or just returned "".
1422        */
1423       tmpbuf[0] = '\1';
1424       tmplen = strftime (tmpbuf, tmpbufsize, locale_format, &tm);
1425
1426       if (tmplen == 0 && tmpbuf[0] != '\0')
1427         {
1428           g_free (tmpbuf);
1429           tmpbufsize *= 2;
1430
1431           if (tmpbufsize > 65536)
1432             {
1433               g_warning (G_STRLOC "Maximum buffer size for g_date_strftime exceeded: giving up\n");
1434               g_free (locale_format);
1435
1436               s[0] = '\0';
1437               return 0;
1438             }
1439         }
1440       else
1441         break;
1442     }
1443   g_free (locale_format);
1444
1445   convbuf = g_locale_to_utf8 (tmpbuf, tmplen, NULL, &convlen, &error);
1446   g_free (tmpbuf);
1447
1448   if (error)
1449     {
1450       g_warning (G_STRLOC "Error converting results of strftime to UTF-8: %s\n", error->message);
1451       g_error_free (error);
1452
1453       s[0] = '\0';
1454       return 0;
1455     }
1456
1457   if (slen <= convlen)
1458     {
1459       /* Ensure only whole characters are copied into the buffer.
1460        */
1461       gchar *end = g_utf8_find_prev_char (convbuf, convbuf + slen);
1462       g_assert (end != NULL);
1463       convlen = end - convbuf;
1464
1465       /* Return 0 because the buffer isn't large enough.
1466        */
1467       retval = 0;
1468     }
1469   else
1470     retval = convlen;
1471
1472   memcpy (s, convbuf, convlen);
1473   s[convlen] = '\0';
1474   g_free (convbuf);
1475
1476   return retval;
1477 }
1478