More include cleanups
[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 <time.h>
39 #include <string.h>
40 #include <stdlib.h>
41 #include <locale.h>
42
43 #ifdef G_OS_WIN32
44 #include <windows.h>
45 #endif
46
47 #include "gdate.h"
48
49 #include "gconvert.h"
50 #include "gmem.h"
51 #include "gstrfuncs.h"
52 #include "gtestutils.h"
53 #include "gthread.h"
54 #include "gunicode.h"
55
56 GDate*
57 g_date_new (void)
58 {
59   GDate *d = g_new0 (GDate, 1); /* happily, 0 is the invalid flag for everything. */
60   
61   return d;
62 }
63
64 GDate*
65 g_date_new_dmy (GDateDay   day, 
66                 GDateMonth m, 
67                 GDateYear  y)
68 {
69   GDate *d;
70   g_return_val_if_fail (g_date_valid_dmy (day, m, y), NULL);
71   
72   d = g_new (GDate, 1);
73   
74   d->julian = FALSE;
75   d->dmy    = TRUE;
76   
77   d->month = m;
78   d->day   = day;
79   d->year  = y;
80   
81   g_assert (g_date_valid (d));
82   
83   return d;
84 }
85
86 GDate*
87 g_date_new_julian (guint32 j)
88 {
89   GDate *d;
90   g_return_val_if_fail (g_date_valid_julian (j), NULL);
91   
92   d = g_new (GDate, 1);
93   
94   d->julian = TRUE;
95   d->dmy    = FALSE;
96   
97   d->julian_days = j;
98   
99   g_assert (g_date_valid (d));
100   
101   return d;
102 }
103
104 void
105 g_date_free (GDate *d)
106 {
107   g_return_if_fail (d != NULL);
108   
109   g_free (d);
110 }
111
112 gboolean     
113 g_date_valid (const GDate *d)
114 {
115   g_return_val_if_fail (d != NULL, FALSE);
116   
117   return (d->julian || d->dmy);
118 }
119
120 static const guint8 days_in_months[2][13] = 
121 {  /* error, jan feb mar apr may jun jul aug sep oct nov dec */
122   {  0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, 
123   {  0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } /* leap year */
124 };
125
126 static const guint16 days_in_year[2][14] = 
127 {  /* 0, jan feb mar apr may  jun  jul  aug  sep  oct  nov  dec */
128   {  0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, 
129   {  0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
130 };
131
132 gboolean     
133 g_date_valid_month (GDateMonth m)
134
135   return ( (m > G_DATE_BAD_MONTH) && (m < 13) );
136 }
137
138 gboolean     
139 g_date_valid_year (GDateYear y)
140 {
141   return ( y > G_DATE_BAD_YEAR );
142 }
143
144 gboolean     
145 g_date_valid_day (GDateDay d)
146 {
147   return ( (d > G_DATE_BAD_DAY) && (d < 32) );
148 }
149
150 gboolean     
151 g_date_valid_weekday (GDateWeekday w)
152 {
153   return ( (w > G_DATE_BAD_WEEKDAY) && (w < 8) );
154 }
155
156 gboolean     
157 g_date_valid_julian (guint32 j)
158 {
159   return (j > G_DATE_BAD_JULIAN);
160 }
161
162 gboolean     
163 g_date_valid_dmy (GDateDay   d, 
164                   GDateMonth m, 
165                   GDateYear  y)
166 {
167   return ( (m > G_DATE_BAD_MONTH) &&
168            (m < 13)               && 
169            (d > G_DATE_BAD_DAY)   && 
170            (y > G_DATE_BAD_YEAR)  &&   /* must check before using g_date_is_leap_year */
171            (d <=  (g_date_is_leap_year (y) ? 
172                    days_in_months[1][m] : days_in_months[0][m])) );
173 }
174
175
176 /* "Julian days" just means an absolute number of days, where Day 1 ==
177  *   Jan 1, Year 1
178  */
179 static void
180 g_date_update_julian (const GDate *const_d)
181 {
182   GDate *d = (GDate *) const_d;
183   GDateYear year;
184   gint idx;
185   
186   g_return_if_fail (d != NULL);
187   g_return_if_fail (d->dmy);
188   g_return_if_fail (!d->julian);
189   g_return_if_fail (g_date_valid_dmy (d->day, d->month, d->year));
190   
191   /* What we actually do is: multiply years * 365 days in the year,
192    * add the number of years divided by 4, subtract the number of
193    * years divided by 100 and add the number of years divided by 400,
194    * which accounts for leap year stuff. Code from Steffen Beyer's
195    * DateCalc. 
196    */
197   
198   year = d->year - 1; /* we know d->year > 0 since it's valid */
199   
200   d->julian_days = year * 365U;
201   d->julian_days += (year >>= 2); /* divide by 4 and add */
202   d->julian_days -= (year /= 25); /* divides original # years by 100 */
203   d->julian_days += year >> 2;    /* divides by 4, which divides original by 400 */
204   
205   idx = g_date_is_leap_year (d->year) ? 1 : 0;
206   
207   d->julian_days += days_in_year[idx][d->month] + d->day;
208   
209   g_return_if_fail (g_date_valid_julian (d->julian_days));
210   
211   d->julian = TRUE;
212 }
213
214 static void 
215 g_date_update_dmy (const GDate *const_d)
216 {
217   GDate *d = (GDate *) const_d;
218   GDateYear y;
219   GDateMonth m;
220   GDateDay day;
221   
222   guint32 A, B, C, D, E, M;
223   
224   g_return_if_fail (d != NULL);
225   g_return_if_fail (d->julian);
226   g_return_if_fail (!d->dmy);
227   g_return_if_fail (g_date_valid_julian (d->julian_days));
228   
229   /* Formula taken from the Calendar FAQ; the formula was for the
230    *  Julian Period which starts on 1 January 4713 BC, so we add
231    *  1,721,425 to the number of days before doing the formula.
232    *
233    * I'm sure this can be simplified for our 1 January 1 AD period
234    * start, but I can't figure out how to unpack the formula.  
235    */
236   
237   A = d->julian_days + 1721425 + 32045;
238   B = ( 4 *(A + 36524) )/ 146097 - 1;
239   C = A - (146097 * B)/4;
240   D = ( 4 * (C + 365) ) / 1461 - 1;
241   E = C - ((1461*D) / 4);
242   M = (5 * (E - 1) + 2)/153;
243   
244   m = M + 3 - (12*(M/10));
245   day = E - (153*M + 2)/5;
246   y = 100 * B + D - 4800 + (M/10);
247   
248 #ifdef G_ENABLE_DEBUG
249   if (!g_date_valid_dmy (day, m, y)) 
250     g_warning ("\nOOPS julian: %u  computed dmy: %u %u %u\n", 
251                d->julian_days, day, m, y);
252 #endif
253   
254   d->month = m;
255   d->day   = day;
256   d->year  = y;
257   
258   d->dmy = TRUE;
259 }
260
261 GDateWeekday 
262 g_date_get_weekday (const GDate *d)
263 {
264   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_WEEKDAY);
265   
266   if (!d->julian) 
267     g_date_update_julian (d);
268
269   g_return_val_if_fail (d->julian, G_DATE_BAD_WEEKDAY);
270   
271   return ((d->julian_days - 1) % 7) + 1;
272 }
273
274 GDateMonth   
275 g_date_get_month (const GDate *d)
276 {
277   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_MONTH);
278   
279   if (!d->dmy) 
280     g_date_update_dmy (d);
281
282   g_return_val_if_fail (d->dmy, G_DATE_BAD_MONTH);
283   
284   return d->month;
285 }
286
287 GDateYear    
288 g_date_get_year (const GDate *d)
289 {
290   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_YEAR);
291   
292   if (!d->dmy) 
293     g_date_update_dmy (d);
294
295   g_return_val_if_fail (d->dmy, G_DATE_BAD_YEAR);  
296   
297   return d->year;
298 }
299
300 GDateDay     
301 g_date_get_day (const GDate *d)
302 {
303   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_DAY);
304   
305   if (!d->dmy) 
306     g_date_update_dmy (d);
307
308   g_return_val_if_fail (d->dmy, G_DATE_BAD_DAY);  
309   
310   return d->day;
311 }
312
313 guint32      
314 g_date_get_julian (const GDate *d)
315 {
316   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_JULIAN);
317   
318   if (!d->julian) 
319     g_date_update_julian (d);
320
321   g_return_val_if_fail (d->julian, G_DATE_BAD_JULIAN);  
322   
323   return d->julian_days;
324 }
325
326 guint        
327 g_date_get_day_of_year (const GDate *d)
328 {
329   gint idx;
330   
331   g_return_val_if_fail (g_date_valid (d), 0);
332   
333   if (!d->dmy) 
334     g_date_update_dmy (d);
335
336   g_return_val_if_fail (d->dmy, 0);  
337   
338   idx = g_date_is_leap_year (d->year) ? 1 : 0;
339   
340   return (days_in_year[idx][d->month] + d->day);
341 }
342
343 guint        
344 g_date_get_monday_week_of_year (const GDate *d)
345 {
346   GDateWeekday wd;
347   guint day;
348   GDate first;
349   
350   g_return_val_if_fail (g_date_valid (d), 0);
351   
352   if (!d->dmy) 
353     g_date_update_dmy (d);
354
355   g_return_val_if_fail (d->dmy, 0);  
356   
357   g_date_clear (&first, 1);
358   
359   g_date_set_dmy (&first, 1, 1, d->year);
360   
361   wd = g_date_get_weekday (&first) - 1; /* make Monday day 0 */
362   day = g_date_get_day_of_year (d) - 1;
363   
364   return ((day + wd)/7U + (wd == 0 ? 1 : 0));
365 }
366
367 guint        
368 g_date_get_sunday_week_of_year (const GDate *d)
369 {
370   GDateWeekday wd;
371   guint day;
372   GDate first;
373   
374   g_return_val_if_fail (g_date_valid (d), 0);
375   
376   if (!d->dmy) 
377     g_date_update_dmy (d);
378
379   g_return_val_if_fail (d->dmy, 0);  
380   
381   g_date_clear (&first, 1);
382   
383   g_date_set_dmy (&first, 1, 1, d->year);
384   
385   wd = g_date_get_weekday (&first);
386   if (wd == 7) wd = 0; /* make Sunday day 0 */
387   day = g_date_get_day_of_year (d) - 1;
388   
389   return ((day + wd)/7U + (wd == 0 ? 1 : 0));
390 }
391
392 /**
393  * g_date_get_iso8601_week_of_year:
394  * @date: a valid #GDate
395  *
396  * Returns the week of the year, where weeks are interpreted according
397  * to ISO 8601. 
398  * 
399  * Returns: ISO 8601 week number of the year.
400  *
401  * Since: 2.6
402  **/
403 guint
404 g_date_get_iso8601_week_of_year (const GDate *d)
405 {
406   guint j, d4, L, d1, w;
407
408   g_return_val_if_fail (g_date_valid (d), 0);
409   
410   if (!d->julian)
411     g_date_update_julian (d);
412
413   g_return_val_if_fail (d->julian, 0);
414
415   /* Formula taken from the Calendar FAQ; the formula was for the
416    * Julian Period which starts on 1 January 4713 BC, so we add
417    * 1,721,425 to the number of days before doing the formula. 
418    */
419   j  = d->julian_days + 1721425;
420   d4 = (j + 31741 - (j % 7)) % 146097 % 36524 % 1461;
421   L  = d4 / 1460;
422   d1 = ((d4 - L) % 365) + L;
423   w  = d1 / 7 + 1;
424
425   return w;
426 }
427
428 gint
429 g_date_days_between (const GDate *d1,
430                      const GDate *d2)
431 {
432   g_return_val_if_fail (g_date_valid (d1), 0);
433   g_return_val_if_fail (g_date_valid (d2), 0);
434
435   return (gint)g_date_get_julian (d2) - (gint)g_date_get_julian (d1);
436 }
437
438 void         
439 g_date_clear (GDate *d, guint ndates)
440 {
441   g_return_if_fail (d != NULL);
442   g_return_if_fail (ndates != 0);
443   
444   memset (d, 0x0, ndates*sizeof (GDate)); 
445 }
446
447 G_LOCK_DEFINE_STATIC (g_date_global);
448
449 /* These are for the parser, output to the user should use *
450  * g_date_strftime () - this creates more never-freed memory to annoy
451  * all those memory debugger users. :-) 
452  */
453
454 static gchar *long_month_names[13] = 
455
456   NULL,
457 };
458
459 static gchar *short_month_names[13] = 
460 {
461   NULL, 
462 };
463
464 /* This tells us if we need to update the parse info */
465 static gchar *current_locale = NULL;
466
467 /* order of these in the current locale */
468 static GDateDMY dmy_order[3] = 
469 {
470    G_DATE_DAY, G_DATE_MONTH, G_DATE_YEAR
471 };
472
473 /* Where to chop two-digit years: i.e., for the 1930 default, numbers
474  * 29 and below are counted as in the year 2000, numbers 30 and above
475  * are counted as in the year 1900.  
476  */
477
478 static const GDateYear twodigit_start_year = 1930;
479
480 /* It is impossible to enter a year between 1 AD and 99 AD with this
481  * in effect.  
482  */
483 static gboolean using_twodigit_years = FALSE;
484
485 /* Adjustment of locale era to AD, non-zero means using locale era
486  */
487 static gint locale_era_adjust = 0;
488
489 struct _GDateParseTokens {
490   gint num_ints;
491   gint n[3];
492   guint month;
493 };
494
495 typedef struct _GDateParseTokens GDateParseTokens;
496
497 #define NUM_LEN 10
498
499 /* HOLDS: g_date_global_lock */
500 static void
501 g_date_fill_parse_tokens (const gchar *str, GDateParseTokens *pt)
502 {
503   gchar num[4][NUM_LEN+1];
504   gint i;
505   const guchar *s;
506   
507   /* We count 4, but store 3; so we can give an error
508    * if there are 4.
509    */
510   num[0][0] = num[1][0] = num[2][0] = num[3][0] = '\0';
511   
512   s = (const guchar *) str;
513   pt->num_ints = 0;
514   while (*s && pt->num_ints < 4) 
515     {
516       
517       i = 0;
518       while (*s && g_ascii_isdigit (*s) && i < NUM_LEN)
519         {
520           num[pt->num_ints][i] = *s;
521           ++s; 
522           ++i;
523         }
524       
525       if (i > 0) 
526         {
527           num[pt->num_ints][i] = '\0';
528           ++(pt->num_ints);
529         }
530       
531       if (*s == '\0') break;
532       
533       ++s;
534     }
535   
536   pt->n[0] = pt->num_ints > 0 ? atoi (num[0]) : 0;
537   pt->n[1] = pt->num_ints > 1 ? atoi (num[1]) : 0;
538   pt->n[2] = pt->num_ints > 2 ? atoi (num[2]) : 0;
539   
540   pt->month = G_DATE_BAD_MONTH;
541   
542   if (pt->num_ints < 3)
543     {
544       gchar *casefold;
545       gchar *normalized;
546       
547       casefold = g_utf8_casefold (str, -1);
548       normalized = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
549       g_free (casefold);
550
551       i = 1;
552       while (i < 13)
553         {
554           if (long_month_names[i] != NULL) 
555             {
556               const gchar *found = strstr (normalized, long_month_names[i]);
557               
558               if (found != NULL)
559                 {
560                   pt->month = i;
561                   break;
562                 }
563             }
564           
565           if (short_month_names[i] != NULL) 
566             {
567               const gchar *found = strstr (normalized, short_month_names[i]);
568               
569               if (found != NULL)
570                 {
571                   pt->month = i;
572                   break;
573                 }
574             }
575
576           ++i;
577         }
578
579       g_free (normalized);
580     }
581 }
582
583 /* HOLDS: g_date_global_lock */
584 static void
585 g_date_prepare_to_parse (const gchar      *str, 
586                          GDateParseTokens *pt)
587 {
588   const gchar *locale = setlocale (LC_TIME, NULL);
589   gboolean recompute_localeinfo = FALSE;
590   GDate d;
591   
592   g_return_if_fail (locale != NULL); /* should not happen */
593   
594   g_date_clear (&d, 1);              /* clear for scratch use */
595   
596   if ( (current_locale == NULL) || (strcmp (locale, current_locale) != 0) ) 
597     recompute_localeinfo = TRUE;  /* Uh, there used to be a reason for the temporary */
598   
599   if (recompute_localeinfo)
600     {
601       int i = 1;
602       GDateParseTokens testpt;
603       gchar buf[128];
604       
605       g_free (current_locale); /* still works if current_locale == NULL */
606       
607       current_locale = g_strdup (locale);
608       
609       short_month_names[0] = "Error";
610       long_month_names[0] = "Error";
611
612       while (i < 13) 
613         {
614           gchar *casefold;
615           
616           g_date_set_dmy (&d, 1, i, 1);
617           
618           g_return_if_fail (g_date_valid (&d));
619           
620           g_date_strftime (buf, 127, "%b", &d);
621
622           casefold = g_utf8_casefold (buf, -1);
623           g_free (short_month_names[i]);
624           short_month_names[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
625           g_free (casefold);
626           
627           g_date_strftime (buf, 127, "%B", &d);
628           casefold = g_utf8_casefold (buf, -1);
629           g_free (long_month_names[i]);
630           long_month_names[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
631           g_free (casefold);
632           
633           ++i;
634         }
635       
636       /* Determine DMY order */
637       
638       /* had to pick a random day - don't change this, some strftimes
639        * are broken on some days, and this one is good so far. */
640       g_date_set_dmy (&d, 4, 7, 1976);
641       
642       g_date_strftime (buf, 127, "%x", &d);
643       
644       g_date_fill_parse_tokens (buf, &testpt);
645       
646       i = 0;
647       while (i < testpt.num_ints)
648         {
649           switch (testpt.n[i])
650             {
651             case 7:
652               dmy_order[i] = G_DATE_MONTH;
653               break;
654             case 4:
655               dmy_order[i] = G_DATE_DAY;
656               break;
657             case 76:
658               using_twodigit_years = TRUE; /* FALL THRU */
659             case 1976:
660               dmy_order[i] = G_DATE_YEAR;
661               break;
662             default:
663               /* assume locale era */
664               locale_era_adjust = 1976 - testpt.n[i];
665               dmy_order[i] = G_DATE_YEAR;
666               break;
667             }
668           ++i;
669         }
670       
671 #ifdef G_ENABLE_DEBUG
672       DEBUG_MSG (("**GDate prepared a new set of locale-specific parse rules."));
673       i = 1;
674       while (i < 13) 
675         {
676           DEBUG_MSG (("  %s   %s", long_month_names[i], short_month_names[i]));
677           ++i;
678         }
679       if (using_twodigit_years)
680         {
681           DEBUG_MSG (("**Using twodigit years with cutoff year: %u", twodigit_start_year));
682         }
683       { 
684         gchar *strings[3];
685         i = 0;
686         while (i < 3)
687           {
688             switch (dmy_order[i])
689               {
690               case G_DATE_MONTH:
691                 strings[i] = "Month";
692                 break;
693               case G_DATE_YEAR:
694                 strings[i] = "Year";
695                 break;
696               case G_DATE_DAY:
697                 strings[i] = "Day";
698                 break;
699               default:
700                 strings[i] = NULL;
701                 break;
702               }
703             ++i;
704           }
705         DEBUG_MSG (("**Order: %s, %s, %s", strings[0], strings[1], strings[2]));
706         DEBUG_MSG (("**Sample date in this locale: `%s'", buf));
707       }
708 #endif
709     }
710   
711   g_date_fill_parse_tokens (str, pt);
712 }
713
714 void         
715 g_date_set_parse (GDate       *d, 
716                   const gchar *str)
717 {
718   GDateParseTokens pt;
719   guint m = G_DATE_BAD_MONTH, day = G_DATE_BAD_DAY, y = G_DATE_BAD_YEAR;
720   
721   g_return_if_fail (d != NULL);
722   
723   /* set invalid */
724   g_date_clear (d, 1);
725   
726   G_LOCK (g_date_global);
727
728   g_date_prepare_to_parse (str, &pt);
729   
730   DEBUG_MSG (("Found %d ints, `%d' `%d' `%d' and written out month %d", 
731               pt.num_ints, pt.n[0], pt.n[1], pt.n[2], pt.month));
732   
733   
734   if (pt.num_ints == 4) 
735     {
736       G_UNLOCK (g_date_global);
737       return; /* presumably a typo; bail out. */
738     }
739   
740   if (pt.num_ints > 1)
741     {
742       int i = 0;
743       int j = 0;
744       
745       g_assert (pt.num_ints < 4); /* i.e., it is 2 or 3 */
746       
747       while (i < pt.num_ints && j < 3) 
748         {
749           switch (dmy_order[j])
750             {
751             case G_DATE_MONTH:
752             {
753               if (pt.num_ints == 2 && pt.month != G_DATE_BAD_MONTH)
754                 {
755                   m = pt.month;
756                   ++j;      /* skip months, but don't skip this number */
757                   continue;
758                 }
759               else 
760                 m = pt.n[i];
761             }
762             break;
763             case G_DATE_DAY:
764             {
765               if (pt.num_ints == 2 && pt.month == G_DATE_BAD_MONTH)
766                 {
767                   day = 1;
768                   ++j;      /* skip days, since we may have month/year */
769                   continue;
770                 }
771               day = pt.n[i];
772             }
773             break;
774             case G_DATE_YEAR:
775             {
776               y  = pt.n[i];
777               
778               if (locale_era_adjust != 0)
779                 {
780                   y += locale_era_adjust;
781                 }
782               else if (using_twodigit_years && y < 100)
783                 {
784                   guint two     =  twodigit_start_year % 100;
785                   guint century = (twodigit_start_year / 100) * 100;
786                   
787                   if (y < two)
788                     century += 100;
789                   
790                   y += century;
791                 }
792             }
793             break;
794             default:
795               break;
796             }
797           
798           ++i;
799           ++j;
800         }
801       
802       
803       if (pt.num_ints == 3 && !g_date_valid_dmy (day, m, y))
804         {
805           /* Try YYYY MM DD */
806           y   = pt.n[0];
807           m   = pt.n[1];
808           day = pt.n[2];
809           
810           if (using_twodigit_years && y < 100) 
811             y = G_DATE_BAD_YEAR; /* avoids ambiguity */
812         }
813       else if (pt.num_ints == 2)
814         {
815           if (m == G_DATE_BAD_MONTH && pt.month != G_DATE_BAD_MONTH)
816             m = pt.month;
817         }
818     }
819   else if (pt.num_ints == 1) 
820     {
821       if (pt.month != G_DATE_BAD_MONTH)
822         {
823           /* Month name and year? */
824           m    = pt.month;
825           day  = 1;
826           y = pt.n[0];
827         }
828       else
829         {
830           /* Try yyyymmdd and yymmdd */
831           
832           m   = (pt.n[0]/100) % 100;
833           day = pt.n[0] % 100;
834           y   = pt.n[0]/10000;
835           
836           /* FIXME move this into a separate function */
837           if (using_twodigit_years && y < 100)
838             {
839               guint two     =  twodigit_start_year % 100;
840               guint century = (twodigit_start_year / 100) * 100;
841               
842               if (y < two)
843                 century += 100;
844               
845               y += century;
846             }
847         }
848     }
849   
850   /* See if we got anything valid out of all this. */
851   /* y < 8000 is to catch 19998 style typos; the library is OK up to 65535 or so */
852   if (y < 8000 && g_date_valid_dmy (day, m, y)) 
853     {
854       d->month = m;
855       d->day   = day;
856       d->year  = y;
857       d->dmy   = TRUE;
858     }
859 #ifdef G_ENABLE_DEBUG
860   else 
861     {
862       DEBUG_MSG (("Rejected DMY %u %u %u", day, m, y));
863     }
864 #endif
865   G_UNLOCK (g_date_global);
866 }
867
868 /**
869  * g_date_set_time_t:
870  * @date: a #GDate 
871  * @timet: <type>time_t</type> value to set
872  *
873  * Sets the value of a date to the date corresponding to a time 
874  * specified as a time_t. The time to date conversion is done using 
875  * the user's current timezone.
876  *
877  * To set the value of a date to the current day, you could write:
878  * |[
879  *  g_date_set_time_t (date, time (NULL)); 
880  * ]|
881  *
882  * Since: 2.10
883  */
884 void         
885 g_date_set_time_t (GDate *date,
886                    time_t timet)
887 {
888   struct tm tm;
889   
890   g_return_if_fail (date != NULL);
891   
892 #ifdef HAVE_LOCALTIME_R
893   localtime_r (&timet, &tm);
894 #else
895   {
896     struct tm *ptm = localtime (&timet);
897
898     if (ptm == NULL)
899       {
900         /* Happens at least in Microsoft's C library if you pass a
901          * negative time_t. Use 2000-01-01 as default date.
902          */
903 #ifndef G_DISABLE_CHECKS
904         g_return_if_fail_warning (G_LOG_DOMAIN, "g_date_set_time", "ptm != NULL");
905 #endif
906
907         tm.tm_mon = 0;
908         tm.tm_mday = 1;
909         tm.tm_year = 100;
910       }
911     else
912       memcpy ((void *) &tm, (void *) ptm, sizeof(struct tm));
913   }
914 #endif
915   
916   date->julian = FALSE;
917   
918   date->month = tm.tm_mon + 1;
919   date->day   = tm.tm_mday;
920   date->year  = tm.tm_year + 1900;
921   
922   g_return_if_fail (g_date_valid_dmy (date->day, date->month, date->year));
923   
924   date->dmy    = TRUE;
925 }
926
927
928 /**
929  * g_date_set_time:
930  * @date: a #GDate.
931  * @time_: #GTime value to set.
932  *
933  * Sets the value of a date from a #GTime value.
934  * The time to date conversion is done using the user's current timezone.
935  *
936  * Deprecated: 2.10: Use g_date_set_time_t() instead.
937  */
938 void
939 g_date_set_time (GDate *date,
940                  GTime  time_)
941 {
942   g_date_set_time_t (date, (time_t) time_);
943 }
944
945 /**
946  * g_date_set_time_val:
947  * @date: a #GDate 
948  * @timeval: #GTimeVal value to set
949  *
950  * Sets the value of a date from a #GTimeVal value.  Note that the
951  * @tv_usec member is ignored, because #GDate can't make use of the
952  * additional precision.
953  *
954  * The time to date conversion is done using the user's current timezone.
955  *
956  * Since: 2.10
957  */
958 void
959 g_date_set_time_val (GDate    *date,
960                      GTimeVal *timeval)
961 {
962   g_date_set_time_t (date, (time_t) timeval->tv_sec);
963 }
964
965 void         
966 g_date_set_month (GDate     *d, 
967                   GDateMonth m)
968 {
969   g_return_if_fail (d != NULL);
970   g_return_if_fail (g_date_valid_month (m));
971
972   if (d->julian && !d->dmy) g_date_update_dmy(d);
973   d->julian = FALSE;
974   
975   d->month = m;
976   
977   if (g_date_valid_dmy (d->day, d->month, d->year))
978     d->dmy = TRUE;
979   else 
980     d->dmy = FALSE;
981 }
982
983 void         
984 g_date_set_day (GDate    *d, 
985                 GDateDay  day)
986 {
987   g_return_if_fail (d != NULL);
988   g_return_if_fail (g_date_valid_day (day));
989   
990   if (d->julian && !d->dmy) g_date_update_dmy(d);
991   d->julian = FALSE;
992   
993   d->day = day;
994   
995   if (g_date_valid_dmy (d->day, d->month, d->year))
996     d->dmy = TRUE;
997   else 
998     d->dmy = FALSE;
999 }
1000
1001 void         
1002 g_date_set_year (GDate     *d, 
1003                  GDateYear  y)
1004 {
1005   g_return_if_fail (d != NULL);
1006   g_return_if_fail (g_date_valid_year (y));
1007   
1008   if (d->julian && !d->dmy) g_date_update_dmy(d);
1009   d->julian = FALSE;
1010   
1011   d->year = y;
1012   
1013   if (g_date_valid_dmy (d->day, d->month, d->year))
1014     d->dmy = TRUE;
1015   else 
1016     d->dmy = FALSE;
1017 }
1018
1019 void         
1020 g_date_set_dmy (GDate      *d, 
1021                 GDateDay    day, 
1022                 GDateMonth  m, 
1023                 GDateYear   y)
1024 {
1025   g_return_if_fail (d != NULL);
1026   g_return_if_fail (g_date_valid_dmy (day, m, y));
1027   
1028   d->julian = FALSE;
1029   
1030   d->month = m;
1031   d->day   = day;
1032   d->year  = y;
1033   
1034   d->dmy = TRUE;
1035 }
1036
1037 void         
1038 g_date_set_julian (GDate   *d, 
1039                    guint32  j)
1040 {
1041   g_return_if_fail (d != NULL);
1042   g_return_if_fail (g_date_valid_julian (j));
1043   
1044   d->julian_days = j;
1045   d->julian = TRUE;
1046   d->dmy = FALSE;
1047 }
1048
1049
1050 gboolean     
1051 g_date_is_first_of_month (const GDate *d)
1052 {
1053   g_return_val_if_fail (g_date_valid (d), FALSE);
1054   
1055   if (!d->dmy) 
1056     g_date_update_dmy (d);
1057
1058   g_return_val_if_fail (d->dmy, FALSE);  
1059   
1060   if (d->day == 1) return TRUE;
1061   else return FALSE;
1062 }
1063
1064 gboolean     
1065 g_date_is_last_of_month (const GDate *d)
1066 {
1067   gint idx;
1068   
1069   g_return_val_if_fail (g_date_valid (d), FALSE);
1070   
1071   if (!d->dmy) 
1072     g_date_update_dmy (d);
1073
1074   g_return_val_if_fail (d->dmy, FALSE);  
1075   
1076   idx = g_date_is_leap_year (d->year) ? 1 : 0;
1077   
1078   if (d->day == days_in_months[idx][d->month]) return TRUE;
1079   else return FALSE;
1080 }
1081
1082 void         
1083 g_date_add_days (GDate *d, 
1084                  guint  ndays)
1085 {
1086   g_return_if_fail (g_date_valid (d));
1087   
1088   if (!d->julian)
1089     g_date_update_julian (d);
1090
1091   g_return_if_fail (d->julian);
1092   
1093   d->julian_days += ndays;
1094   d->dmy = FALSE;
1095 }
1096
1097 void         
1098 g_date_subtract_days (GDate *d, 
1099                       guint  ndays)
1100 {
1101   g_return_if_fail (g_date_valid (d));
1102   
1103   if (!d->julian)
1104     g_date_update_julian (d);
1105
1106   g_return_if_fail (d->julian);
1107   g_return_if_fail (d->julian_days > ndays);
1108   
1109   d->julian_days -= ndays;
1110   d->dmy = FALSE;
1111 }
1112
1113 void         
1114 g_date_add_months (GDate *d, 
1115                    guint  nmonths)
1116 {
1117   guint years, months;
1118   gint idx;
1119   
1120   g_return_if_fail (g_date_valid (d));
1121   
1122   if (!d->dmy) 
1123     g_date_update_dmy (d);
1124
1125   g_return_if_fail (d->dmy);  
1126   
1127   nmonths += d->month - 1;
1128   
1129   years  = nmonths/12;
1130   months = nmonths%12;
1131   
1132   d->month = months + 1;
1133   d->year  += years;
1134   
1135   idx = g_date_is_leap_year (d->year) ? 1 : 0;
1136   
1137   if (d->day > days_in_months[idx][d->month])
1138     d->day = days_in_months[idx][d->month];
1139   
1140   d->julian = FALSE;
1141   
1142   g_return_if_fail (g_date_valid (d));
1143 }
1144
1145 void         
1146 g_date_subtract_months (GDate *d, 
1147                         guint  nmonths)
1148 {
1149   guint years, months;
1150   gint idx;
1151   
1152   g_return_if_fail (g_date_valid (d));
1153   
1154   if (!d->dmy) 
1155     g_date_update_dmy (d);
1156
1157   g_return_if_fail (d->dmy);  
1158   
1159   years  = nmonths/12;
1160   months = nmonths%12;
1161   
1162   g_return_if_fail (d->year > years);
1163   
1164   d->year  -= years;
1165   
1166   if (d->month > months) d->month -= months;
1167   else 
1168     {
1169       months -= d->month;
1170       d->month = 12 - months;
1171       d->year -= 1;
1172     }
1173   
1174   idx = g_date_is_leap_year (d->year) ? 1 : 0;
1175   
1176   if (d->day > days_in_months[idx][d->month])
1177     d->day = days_in_months[idx][d->month];
1178   
1179   d->julian = FALSE;
1180   
1181   g_return_if_fail (g_date_valid (d));
1182 }
1183
1184 void         
1185 g_date_add_years (GDate *d, 
1186                   guint  nyears)
1187 {
1188   g_return_if_fail (g_date_valid (d));
1189   
1190   if (!d->dmy) 
1191     g_date_update_dmy (d);
1192
1193   g_return_if_fail (d->dmy);  
1194   
1195   d->year += nyears;
1196   
1197   if (d->month == 2 && d->day == 29)
1198     {
1199       if (!g_date_is_leap_year (d->year))
1200         d->day = 28;
1201     }
1202   
1203   d->julian = FALSE;
1204 }
1205
1206 void         
1207 g_date_subtract_years (GDate *d, 
1208                        guint  nyears)
1209 {
1210   g_return_if_fail (g_date_valid (d));
1211   
1212   if (!d->dmy) 
1213     g_date_update_dmy (d);
1214
1215   g_return_if_fail (d->dmy);  
1216   g_return_if_fail (d->year > nyears);
1217   
1218   d->year -= nyears;
1219   
1220   if (d->month == 2 && d->day == 29)
1221     {
1222       if (!g_date_is_leap_year (d->year))
1223         d->day = 28;
1224     }
1225   
1226   d->julian = FALSE;
1227 }
1228
1229 gboolean     
1230 g_date_is_leap_year (GDateYear year)
1231 {
1232   g_return_val_if_fail (g_date_valid_year (year), FALSE);
1233   
1234   return ( (((year % 4) == 0) && ((year % 100) != 0)) ||
1235            (year % 400) == 0 );
1236 }
1237
1238 guint8         
1239 g_date_get_days_in_month (GDateMonth month, 
1240                           GDateYear  year)
1241 {
1242   gint idx;
1243   
1244   g_return_val_if_fail (g_date_valid_year (year), 0);
1245   g_return_val_if_fail (g_date_valid_month (month), 0);
1246   
1247   idx = g_date_is_leap_year (year) ? 1 : 0;
1248   
1249   return days_in_months[idx][month];
1250 }
1251
1252 guint8       
1253 g_date_get_monday_weeks_in_year (GDateYear year)
1254 {
1255   GDate d;
1256   
1257   g_return_val_if_fail (g_date_valid_year (year), 0);
1258   
1259   g_date_clear (&d, 1);
1260   g_date_set_dmy (&d, 1, 1, year);
1261   if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1262   g_date_set_dmy (&d, 31, 12, year);
1263   if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1264   if (g_date_is_leap_year (year)) 
1265     {
1266       g_date_set_dmy (&d, 2, 1, year);
1267       if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1268       g_date_set_dmy (&d, 30, 12, year);
1269       if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1270     }
1271   return 52;
1272 }
1273
1274 guint8       
1275 g_date_get_sunday_weeks_in_year (GDateYear year)
1276 {
1277   GDate d;
1278   
1279   g_return_val_if_fail (g_date_valid_year (year), 0);
1280   
1281   g_date_clear (&d, 1);
1282   g_date_set_dmy (&d, 1, 1, year);
1283   if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1284   g_date_set_dmy (&d, 31, 12, year);
1285   if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1286   if (g_date_is_leap_year (year)) 
1287     {
1288       g_date_set_dmy (&d, 2, 1, year);
1289       if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1290       g_date_set_dmy (&d, 30, 12, year);
1291       if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1292     }
1293   return 52;
1294 }
1295
1296 gint         
1297 g_date_compare (const GDate *lhs, 
1298                 const GDate *rhs)
1299 {
1300   g_return_val_if_fail (lhs != NULL, 0);
1301   g_return_val_if_fail (rhs != NULL, 0);
1302   g_return_val_if_fail (g_date_valid (lhs), 0);
1303   g_return_val_if_fail (g_date_valid (rhs), 0);
1304   
1305   /* Remember the self-comparison case! I think it works right now. */
1306   
1307   while (TRUE)
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     g_date_update_dmy (d);
1357
1358   g_return_if_fail (d->dmy);
1359   
1360   /* zero all the irrelevant fields to be sure they're valid */
1361   
1362   /* On Linux and maybe other systems, there are weird non-POSIX
1363    * fields on the end of struct tm that choke strftime if they
1364    * contain garbage.  So we need to 0 the entire struct, not just the
1365    * fields we know to exist. 
1366    */
1367   
1368   memset (tm, 0x0, sizeof (struct tm));
1369   
1370   tm->tm_mday = d->day;
1371   tm->tm_mon  = d->month - 1; /* 0-11 goes in tm */
1372   tm->tm_year = ((int)d->year) - 1900; /* X/Open says tm_year can be negative */
1373   
1374   day = g_date_get_weekday (d);
1375   if (day == 7) day = 0; /* struct tm wants days since Sunday, so Sunday is 0 */
1376   
1377   tm->tm_wday = (int)day;
1378   
1379   tm->tm_yday = g_date_get_day_of_year (d) - 1; /* 0 to 365 */
1380   tm->tm_isdst = -1; /* -1 means "information not available" */
1381 }
1382
1383 void
1384 g_date_clamp (GDate       *date,
1385               const GDate *min_date,
1386               const GDate *max_date)
1387 {
1388   g_return_if_fail (g_date_valid (date));
1389
1390   if (min_date != NULL)
1391     g_return_if_fail (g_date_valid (min_date));
1392
1393   if (max_date != NULL)
1394     g_return_if_fail (g_date_valid (max_date));
1395
1396   if (min_date != NULL && max_date != NULL)
1397     g_return_if_fail (g_date_compare (min_date, max_date) <= 0);
1398
1399   if (min_date && g_date_compare (date, min_date) < 0)
1400     *date = *min_date;
1401
1402   if (max_date && g_date_compare (max_date, date) < 0)
1403     *date = *max_date;
1404 }
1405
1406 void
1407 g_date_order (GDate *date1,
1408               GDate *date2)
1409 {
1410   g_return_if_fail (g_date_valid (date1));
1411   g_return_if_fail (g_date_valid (date2));
1412
1413   if (g_date_compare (date1, date2) > 0)
1414     {
1415       GDate tmp = *date1;
1416       *date1 = *date2;
1417       *date2 = tmp;
1418     }
1419 }
1420
1421 #ifdef G_OS_WIN32
1422 static gsize
1423 win32_strftime_helper (const GDate     *d,
1424                        const gchar     *format,
1425                        const struct tm *tm,
1426                        gchar           *s,
1427                        gsize            slen)
1428 {
1429   SYSTEMTIME systemtime;
1430   TIME_ZONE_INFORMATION tzinfo;
1431   LCID lcid;
1432   int n, k;
1433   GArray *result;
1434   const gchar *p;
1435   gunichar c;
1436   const wchar_t digits[] = L"0123456789";
1437   gchar *convbuf;
1438   glong convlen = 0;
1439   gsize retval;
1440
1441   systemtime.wYear = tm->tm_year + 1900;
1442   systemtime.wMonth = tm->tm_mon + 1;
1443   systemtime.wDayOfWeek = tm->tm_wday;
1444   systemtime.wDay = tm->tm_mday;
1445   systemtime.wHour = tm->tm_hour;
1446   systemtime.wMinute = tm->tm_min;
1447   systemtime.wSecond = tm->tm_sec;
1448   systemtime.wMilliseconds = 0;
1449   
1450   lcid = GetThreadLocale ();
1451   result = g_array_sized_new (FALSE, FALSE, sizeof (wchar_t), MAX (128, strlen (format) * 2));
1452
1453   p = format;
1454   while (*p)
1455     {
1456       c = g_utf8_get_char (p);
1457       if (c == '%')
1458         {
1459           p = g_utf8_next_char (p);
1460           if (!*p)
1461             {
1462               s[0] = '\0';
1463               g_array_free (result, TRUE);
1464
1465               return 0;
1466             }
1467           
1468           c = g_utf8_get_char (p);
1469           if (c == 'E' || c == 'O')
1470             {
1471               /* Ignore modified conversion specifiers for now. */
1472               p = g_utf8_next_char (p);
1473               if (!*p)
1474                 {
1475                   s[0] = '\0';
1476                   g_array_free (result, TRUE);
1477                   
1478                   return 0;
1479                 }
1480
1481               c = g_utf8_get_char (p);
1482             }
1483
1484           switch (c)
1485             {
1486             case 'a':
1487               if (systemtime.wDayOfWeek == 0)
1488                 k = 6;
1489               else
1490                 k = systemtime.wDayOfWeek - 1;
1491               n = GetLocaleInfoW (lcid, LOCALE_SABBREVDAYNAME1+k, NULL, 0);
1492               g_array_set_size (result, result->len + n);
1493               GetLocaleInfoW (lcid, LOCALE_SABBREVDAYNAME1+k, ((wchar_t *) result->data) + result->len - n, n);
1494               g_array_set_size (result, result->len - 1);
1495               break;
1496             case 'A':
1497               if (systemtime.wDayOfWeek == 0)
1498                 k = 6;
1499               else
1500                 k = systemtime.wDayOfWeek - 1;
1501               n = GetLocaleInfoW (lcid, LOCALE_SDAYNAME1+k, NULL, 0);
1502               g_array_set_size (result, result->len + n);
1503               GetLocaleInfoW (lcid, LOCALE_SDAYNAME1+k, ((wchar_t *) result->data) + result->len - n, n);
1504               g_array_set_size (result, result->len - 1);
1505               break;
1506             case 'b':
1507             case 'h':
1508               n = GetLocaleInfoW (lcid, LOCALE_SABBREVMONTHNAME1+systemtime.wMonth-1, NULL, 0);
1509               g_array_set_size (result, result->len + n);
1510               GetLocaleInfoW (lcid, LOCALE_SABBREVMONTHNAME1+systemtime.wMonth-1, ((wchar_t *) result->data) + result->len - n, n);
1511               g_array_set_size (result, result->len - 1);
1512               break;
1513             case 'B':
1514               n = GetLocaleInfoW (lcid, LOCALE_SMONTHNAME1+systemtime.wMonth-1, NULL, 0);
1515               g_array_set_size (result, result->len + n);
1516               GetLocaleInfoW (lcid, LOCALE_SMONTHNAME1+systemtime.wMonth-1, ((wchar_t *) result->data) + result->len - n, n);
1517               g_array_set_size (result, result->len - 1);
1518               break;
1519             case 'c':
1520               n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
1521               if (n > 0)
1522                 {
1523                   g_array_set_size (result, result->len + n);
1524                   GetDateFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
1525                   g_array_set_size (result, result->len - 1);
1526                 }
1527               g_array_append_vals (result, L" ", 1);
1528               n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
1529               if (n > 0)
1530                 {
1531                   g_array_set_size (result, result->len + n);
1532                   GetTimeFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
1533                   g_array_set_size (result, result->len - 1);
1534                 }
1535               break;
1536             case 'C':
1537               g_array_append_vals (result, digits + systemtime.wYear/1000, 1);
1538               g_array_append_vals (result, digits + (systemtime.wYear/1000)%10, 1);
1539               break;
1540             case 'd':
1541               g_array_append_vals (result, digits + systemtime.wDay/10, 1);
1542               g_array_append_vals (result, digits + systemtime.wDay%10, 1);
1543               break;
1544             case 'D':
1545               g_array_append_vals (result, digits + systemtime.wMonth/10, 1);
1546               g_array_append_vals (result, digits + systemtime.wMonth%10, 1);
1547               g_array_append_vals (result, L"/", 1);
1548               g_array_append_vals (result, digits + systemtime.wDay/10, 1);
1549               g_array_append_vals (result, digits + systemtime.wDay%10, 1);
1550               g_array_append_vals (result, L"/", 1);
1551               g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
1552               g_array_append_vals (result, digits + systemtime.wYear%10, 1);
1553               break;
1554             case 'e':
1555               if (systemtime.wDay >= 10)
1556                 g_array_append_vals (result, digits + systemtime.wDay/10, 1);
1557               else
1558                 g_array_append_vals (result, L" ", 1);
1559               g_array_append_vals (result, digits + systemtime.wDay%10, 1);
1560               break;
1561
1562               /* A GDate has no time fields, so for now we can
1563                * hardcode all time conversions into zeros (or 12 for
1564                * %I). The alternative code snippets in the #else
1565                * branches are here ready to be taken into use when
1566                * needed by a g_strftime() or g_date_and_time_format()
1567                * or whatever.
1568                */
1569             case 'H':
1570 #if 1
1571               g_array_append_vals (result, L"00", 2);
1572 #else
1573               g_array_append_vals (result, digits + systemtime.wHour/10, 1);
1574               g_array_append_vals (result, digits + systemtime.wHour%10, 1);
1575 #endif
1576               break;
1577             case 'I':
1578 #if 1
1579               g_array_append_vals (result, L"12", 2);
1580 #else
1581               if (systemtime.wHour == 0)
1582                 g_array_append_vals (result, L"12", 2);
1583               else
1584                 {
1585                   g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
1586                   g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
1587                 }
1588 #endif
1589               break;
1590             case  'j':
1591               g_array_append_vals (result, digits + (tm->tm_yday+1)/100, 1);
1592               g_array_append_vals (result, digits + ((tm->tm_yday+1)/10)%10, 1);
1593               g_array_append_vals (result, digits + (tm->tm_yday+1)%10, 1);
1594               break;
1595             case 'm':
1596               g_array_append_vals (result, digits + systemtime.wMonth/10, 1);
1597               g_array_append_vals (result, digits + systemtime.wMonth%10, 1);
1598               break;
1599             case 'M':
1600 #if 1
1601               g_array_append_vals (result, L"00", 2);
1602 #else
1603               g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
1604               g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
1605 #endif
1606               break;
1607             case 'n':
1608               g_array_append_vals (result, L"\n", 1);
1609               break;
1610             case 'p':
1611               n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
1612               if (n > 0)
1613                 {
1614                   g_array_set_size (result, result->len + n);
1615                   GetTimeFormatW (lcid, 0, &systemtime, L"tt", ((wchar_t *) result->data) + result->len - n, n);
1616                   g_array_set_size (result, result->len - 1);
1617                 }
1618               break;
1619             case 'r':
1620               /* This is a rather odd format. Hard to say what to do.
1621                * Let's always use the POSIX %I:%M:%S %p
1622                */
1623 #if 1
1624               g_array_append_vals (result, L"12:00:00", 8);
1625 #else
1626               if (systemtime.wHour == 0)
1627                 g_array_append_vals (result, L"12", 2);
1628               else
1629                 {
1630                   g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
1631                   g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
1632                 }
1633               g_array_append_vals (result, L":", 1);
1634               g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
1635               g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
1636               g_array_append_vals (result, L":", 1);
1637               g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
1638               g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
1639               g_array_append_vals (result, L" ", 1);
1640 #endif
1641               n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
1642               if (n > 0)
1643                 {
1644                   g_array_set_size (result, result->len + n);
1645                   GetTimeFormatW (lcid, 0, &systemtime, L"tt", ((wchar_t *) result->data) + result->len - n, n);
1646                   g_array_set_size (result, result->len - 1);
1647                 }
1648               break;
1649             case 'R':
1650 #if 1
1651               g_array_append_vals (result, L"00:00", 5);
1652 #else
1653               g_array_append_vals (result, digits + systemtime.wHour/10, 1);
1654               g_array_append_vals (result, digits + systemtime.wHour%10, 1);
1655               g_array_append_vals (result, L":", 1);
1656               g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
1657               g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
1658 #endif
1659               break;
1660             case 'S':
1661 #if 1
1662               g_array_append_vals (result, L"00", 2);
1663 #else
1664               g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
1665               g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
1666 #endif
1667               break;
1668             case 't':
1669               g_array_append_vals (result, L"\t", 1);
1670               break;
1671             case 'T':
1672 #if 1
1673               g_array_append_vals (result, L"00:00:00", 8);
1674 #else
1675               g_array_append_vals (result, digits + systemtime.wHour/10, 1);
1676               g_array_append_vals (result, digits + systemtime.wHour%10, 1);
1677               g_array_append_vals (result, L":", 1);
1678               g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
1679               g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
1680               g_array_append_vals (result, L":", 1);
1681               g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
1682               g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
1683 #endif
1684               break;
1685             case 'u':
1686               if (systemtime.wDayOfWeek == 0)
1687                 g_array_append_vals (result, L"7", 1);
1688               else
1689                 g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
1690               break;
1691             case 'U':
1692               n = g_date_get_sunday_week_of_year (d);
1693               g_array_append_vals (result, digits + n/10, 1);
1694               g_array_append_vals (result, digits + n%10, 1);
1695               break;
1696             case 'V':
1697               n = g_date_get_iso8601_week_of_year (d);
1698               g_array_append_vals (result, digits + n/10, 1);
1699               g_array_append_vals (result, digits + n%10, 1);
1700               break;
1701             case 'w':
1702               g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
1703               break;
1704             case 'W':
1705               n = g_date_get_monday_week_of_year (d);
1706               g_array_append_vals (result, digits + n/10, 1);
1707               g_array_append_vals (result, digits + n%10, 1);
1708               break;
1709             case 'x':
1710               n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
1711               if (n > 0)
1712                 {
1713                   g_array_set_size (result, result->len + n);
1714                   GetDateFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
1715                   g_array_set_size (result, result->len - 1);
1716                 }
1717               break;
1718             case 'X':
1719               n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
1720               if (n > 0)
1721                 {
1722                   g_array_set_size (result, result->len + n);
1723                   GetTimeFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
1724                   g_array_set_size (result, result->len - 1);
1725                 }
1726               break;
1727             case 'y':
1728               g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
1729               g_array_append_vals (result, digits + systemtime.wYear%10, 1);
1730               break;
1731             case 'Y':
1732               g_array_append_vals (result, digits + systemtime.wYear/1000, 1);
1733               g_array_append_vals (result, digits + (systemtime.wYear/100)%10, 1);
1734               g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
1735               g_array_append_vals (result, digits + systemtime.wYear%10, 1);
1736               break;
1737             case 'Z':
1738               n = GetTimeZoneInformation (&tzinfo);
1739               if (n == TIME_ZONE_ID_UNKNOWN)
1740                 ;
1741               else if (n == TIME_ZONE_ID_STANDARD)
1742                 g_array_append_vals (result, tzinfo.StandardName, wcslen (tzinfo.StandardName));
1743               else if (n == TIME_ZONE_ID_DAYLIGHT)
1744                 g_array_append_vals (result, tzinfo.DaylightName, wcslen (tzinfo.DaylightName));
1745               break;
1746             case '%':
1747               g_array_append_vals (result, L"%", 1);
1748               break;
1749             }      
1750         } 
1751       else if (c <= 0xFFFF)
1752         {
1753           wchar_t wc = c;
1754           g_array_append_vals (result, &wc, 1);
1755         }
1756       else
1757         {
1758           glong nwc;
1759           wchar_t *ws;
1760
1761           ws = g_ucs4_to_utf16 (&c, 1, NULL, &nwc, NULL);
1762           g_array_append_vals (result, ws, nwc);
1763           g_free (ws);
1764         }
1765       p = g_utf8_next_char (p);
1766     }
1767   
1768   convbuf = g_utf16_to_utf8 ((wchar_t *) result->data, result->len, NULL, &convlen, NULL);
1769   g_array_free (result, TRUE);
1770
1771   if (!convbuf)
1772     {
1773       s[0] = '\0';
1774       return 0;
1775     }
1776   
1777   if (slen <= convlen)
1778     {
1779       /* Ensure only whole characters are copied into the buffer. */
1780       gchar *end = g_utf8_find_prev_char (convbuf, convbuf + slen);
1781       g_assert (end != NULL);
1782       convlen = end - convbuf;
1783
1784       /* Return 0 because the buffer isn't large enough. */
1785       retval = 0;
1786     }
1787   else
1788     retval = convlen;
1789
1790   memcpy (s, convbuf, convlen);
1791   s[convlen] = '\0';
1792   g_free (convbuf);
1793
1794   return retval;
1795 }
1796
1797 #endif
1798
1799 gsize     
1800 g_date_strftime (gchar       *s, 
1801                  gsize        slen, 
1802                  const gchar *format, 
1803                  const GDate *d)
1804 {
1805   struct tm tm;
1806 #ifndef G_OS_WIN32
1807   gsize locale_format_len = 0;
1808   gchar *locale_format;
1809   gsize tmplen;
1810   gchar *tmpbuf;
1811   gsize tmpbufsize;
1812   gsize convlen = 0;
1813   gchar *convbuf;
1814   GError *error = NULL;
1815   gsize retval;
1816 #endif
1817
1818   g_return_val_if_fail (g_date_valid (d), 0);
1819   g_return_val_if_fail (slen > 0, 0); 
1820   g_return_val_if_fail (format != NULL, 0);
1821   g_return_val_if_fail (s != NULL, 0);
1822
1823   g_date_to_struct_tm (d, &tm);
1824
1825 #ifdef G_OS_WIN32
1826   if (!g_utf8_validate (format, -1, NULL))
1827     {
1828       s[0] = '\0';
1829       return 0;
1830     }
1831   return win32_strftime_helper (d, format, &tm, s, slen);
1832 #else
1833
1834   locale_format = g_locale_from_utf8 (format, -1, NULL, &locale_format_len, &error);
1835
1836   if (error)
1837     {
1838       g_warning (G_STRLOC "Error converting format to locale encoding: %s\n", error->message);
1839       g_error_free (error);
1840
1841       s[0] = '\0';
1842       return 0;
1843     }
1844
1845   tmpbufsize = MAX (128, locale_format_len * 2);
1846   while (TRUE)
1847     {
1848       tmpbuf = g_malloc (tmpbufsize);
1849
1850       /* Set the first byte to something other than '\0', to be able to
1851        * recognize whether strftime actually failed or just returned "".
1852        */
1853       tmpbuf[0] = '\1';
1854       tmplen = strftime (tmpbuf, tmpbufsize, locale_format, &tm);
1855
1856       if (tmplen == 0 && tmpbuf[0] != '\0')
1857         {
1858           g_free (tmpbuf);
1859           tmpbufsize *= 2;
1860
1861           if (tmpbufsize > 65536)
1862             {
1863               g_warning (G_STRLOC "Maximum buffer size for g_date_strftime exceeded: giving up\n");
1864               g_free (locale_format);
1865
1866               s[0] = '\0';
1867               return 0;
1868             }
1869         }
1870       else
1871         break;
1872     }
1873   g_free (locale_format);
1874
1875   convbuf = g_locale_to_utf8 (tmpbuf, tmplen, NULL, &convlen, &error);
1876   g_free (tmpbuf);
1877
1878   if (error)
1879     {
1880       g_warning (G_STRLOC "Error converting results of strftime to UTF-8: %s\n", error->message);
1881       g_error_free (error);
1882
1883       s[0] = '\0';
1884       return 0;
1885     }
1886
1887   if (slen <= convlen)
1888     {
1889       /* Ensure only whole characters are copied into the buffer.
1890        */
1891       gchar *end = g_utf8_find_prev_char (convbuf, convbuf + slen);
1892       g_assert (end != NULL);
1893       convlen = end - convbuf;
1894
1895       /* Return 0 because the buffer isn't large enough.
1896        */
1897       retval = 0;
1898     }
1899   else
1900     retval = convlen;
1901
1902   memcpy (s, convbuf, convlen);
1903   s[convlen] = '\0';
1904   g_free (convbuf);
1905
1906   return retval;
1907 #endif
1908 }