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