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