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