Improve g_date_clamp docs. (#491970, Areg Beketovski)
[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 index;
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   index = g_date_is_leap_year (d->year) ? 1 : 0;
201   
202   d->julian_days += days_in_year[index][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 index;
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   index = g_date_is_leap_year (d->year) ? 1 : 0;
334   
335   return (days_in_year[index][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         DEBUG_MSG (("**Using twodigit years with cutoff year: %u", twodigit_start_year));
676       { 
677         gchar *strings[3];
678         i = 0;
679         while (i < 3)
680           {
681             switch (dmy_order[i])
682               {
683               case G_DATE_MONTH:
684                 strings[i] = "Month";
685                 break;
686               case G_DATE_YEAR:
687                 strings[i] = "Year";
688                 break;
689               case G_DATE_DAY:
690                 strings[i] = "Day";
691                 break;
692               default:
693                 strings[i] = NULL;
694                 break;
695               }
696             ++i;
697           }
698         DEBUG_MSG (("**Order: %s, %s, %s", strings[0], strings[1], strings[2]));
699         DEBUG_MSG (("**Sample date in this locale: `%s'", buf));
700       }
701 #endif
702     }
703   
704   g_date_fill_parse_tokens (str, pt);
705 }
706
707 void         
708 g_date_set_parse (GDate       *d, 
709                   const gchar *str)
710 {
711   GDateParseTokens pt;
712   guint m = G_DATE_BAD_MONTH, day = G_DATE_BAD_DAY, y = G_DATE_BAD_YEAR;
713   
714   g_return_if_fail (d != NULL);
715   
716   /* set invalid */
717   g_date_clear (d, 1);
718   
719   G_LOCK (g_date_global);
720
721   g_date_prepare_to_parse (str, &pt);
722   
723   DEBUG_MSG (("Found %d ints, `%d' `%d' `%d' and written out month %d", 
724               pt.num_ints, pt.n[0], pt.n[1], pt.n[2], pt.month));
725   
726   
727   if (pt.num_ints == 4) 
728     {
729       G_UNLOCK (g_date_global);
730       return; /* presumably a typo; bail out. */
731     }
732   
733   if (pt.num_ints > 1)
734     {
735       int i = 0;
736       int j = 0;
737       
738       g_assert (pt.num_ints < 4); /* i.e., it is 2 or 3 */
739       
740       while (i < pt.num_ints && j < 3) 
741         {
742           switch (dmy_order[j])
743             {
744             case G_DATE_MONTH:
745             {
746               if (pt.num_ints == 2 && pt.month != G_DATE_BAD_MONTH)
747                 {
748                   m = pt.month;
749                   ++j;      /* skip months, but don't skip this number */
750                   continue;
751                 }
752               else 
753                 m = pt.n[i];
754             }
755             break;
756             case G_DATE_DAY:
757             {
758               if (pt.num_ints == 2 && pt.month == G_DATE_BAD_MONTH)
759                 {
760                   day = 1;
761                   ++j;      /* skip days, since we may have month/year */
762                   continue;
763                 }
764               day = pt.n[i];
765             }
766             break;
767             case G_DATE_YEAR:
768             {
769               y  = pt.n[i];
770               
771               if (locale_era_adjust != 0)
772                 {
773                   y += locale_era_adjust;
774                 }
775               else if (using_twodigit_years && y < 100)
776                 {
777                   guint two     =  twodigit_start_year % 100;
778                   guint century = (twodigit_start_year / 100) * 100;
779                   
780                   if (y < two)
781                     century += 100;
782                   
783                   y += century;
784                 }
785             }
786             break;
787             default:
788               break;
789             }
790           
791           ++i;
792           ++j;
793         }
794       
795       
796       if (pt.num_ints == 3 && !g_date_valid_dmy (day, m, y))
797         {
798           /* Try YYYY MM DD */
799           y   = pt.n[0];
800           m   = pt.n[1];
801           day = pt.n[2];
802           
803           if (using_twodigit_years && y < 100) 
804             y = G_DATE_BAD_YEAR; /* avoids ambiguity */
805         }
806       else if (pt.num_ints == 2)
807         {
808           if (m == G_DATE_BAD_MONTH && pt.month != G_DATE_BAD_MONTH)
809             m = pt.month;
810         }
811     }
812   else if (pt.num_ints == 1) 
813     {
814       if (pt.month != G_DATE_BAD_MONTH)
815         {
816           /* Month name and year? */
817           m    = pt.month;
818           day  = 1;
819           y = pt.n[0];
820         }
821       else
822         {
823           /* Try yyyymmdd and yymmdd */
824           
825           m   = (pt.n[0]/100) % 100;
826           day = pt.n[0] % 100;
827           y   = pt.n[0]/10000;
828           
829           /* FIXME move this into a separate function */
830           if (using_twodigit_years && y < 100)
831             {
832               guint two     =  twodigit_start_year % 100;
833               guint century = (twodigit_start_year / 100) * 100;
834               
835               if (y < two)
836                 century += 100;
837               
838               y += century;
839             }
840         }
841     }
842   
843   /* See if we got anything valid out of all this. */
844   /* y < 8000 is to catch 19998 style typos; the library is OK up to 65535 or so */
845   if (y < 8000 && g_date_valid_dmy (day, m, y)) 
846     {
847       d->month = m;
848       d->day   = day;
849       d->year  = y;
850       d->dmy   = TRUE;
851     }
852 #ifdef G_ENABLE_DEBUG
853   else 
854     DEBUG_MSG (("Rejected DMY %u %u %u", day, m, y));
855 #endif
856   G_UNLOCK (g_date_global);
857 }
858
859 /**
860  * g_date_set_time_t:
861  * @date: a #GDate 
862  * @timet: <type>time_t</type> value to set
863  *
864  * Sets the value of a date from a <type>time_t</type> value. 
865  *
866  * To set the value of a date to the current day, you could write:
867  * <informalexample><programlisting> 
868  *  g_date_set_time_t (date, time (NULL)); 
869  * </programlisting></informalexample>
870  *
871  * Since: 2.10
872  */
873 void         
874 g_date_set_time_t (GDate *date,
875                    time_t timet)
876 {
877   struct tm tm;
878   
879   g_return_if_fail (date != NULL);
880   
881 #ifdef HAVE_LOCALTIME_R
882   localtime_r (&timet, &tm);
883 #else
884   {
885     struct tm *ptm = localtime (&timet);
886
887     if (ptm == NULL)
888       {
889         /* Happens at least in Microsoft's C library if you pass a
890          * negative time_t. Use 2000-01-01 as default date.
891          */
892 #ifndef G_DISABLE_CHECKS
893         g_return_if_fail_warning (G_LOG_DOMAIN, "g_date_set_time", "ptm != NULL");
894 #endif
895
896         tm.tm_mon = 0;
897         tm.tm_mday = 1;
898         tm.tm_year = 100;
899       }
900     else
901       memcpy ((void *) &tm, (void *) ptm, sizeof(struct tm));
902   }
903 #endif
904   
905   date->julian = FALSE;
906   
907   date->month = tm.tm_mon + 1;
908   date->day   = tm.tm_mday;
909   date->year  = tm.tm_year + 1900;
910   
911   g_return_if_fail (g_date_valid_dmy (date->day, date->month, date->year));
912   
913   date->dmy    = TRUE;
914 }
915
916
917 /**
918  * g_date_set_time:
919  * @date: a #GDate.
920  * @time_: #GTime value to set.
921  *
922  * Sets the value of a date from a #GTime value. 
923  *
924  * @Deprecated:2.10: Use g_date_set_time_t() instead.
925  */
926 void
927 g_date_set_time (GDate *date,
928                  GTime  time_)
929 {
930   g_date_set_time_t (date, (time_t) time_);
931 }
932
933 /**
934  * g_date_set_time_val:
935  * @date: a #GDate 
936  * @timeval: #GTimeVal value to set
937  *
938  * Sets the value of a date from a #GTimeVal value.  Note that the
939  * @tv_usec member is ignored, because #GDate can't make use of the
940  * additional precision.
941  *
942  * Since: 2.10
943  */
944 void
945 g_date_set_time_val (GDate    *date,
946                      GTimeVal *timeval)
947 {
948   g_date_set_time_t (date, (time_t) timeval->tv_sec);
949 }
950
951 void         
952 g_date_set_month (GDate     *d, 
953                   GDateMonth m)
954 {
955   g_return_if_fail (d != NULL);
956   g_return_if_fail (g_date_valid_month (m));
957
958   if (d->julian && !d->dmy) g_date_update_dmy(d);
959   d->julian = FALSE;
960   
961   d->month = m;
962   
963   if (g_date_valid_dmy (d->day, d->month, d->year))
964     d->dmy = TRUE;
965   else 
966     d->dmy = FALSE;
967 }
968
969 void         
970 g_date_set_day (GDate    *d, 
971                 GDateDay  day)
972 {
973   g_return_if_fail (d != NULL);
974   g_return_if_fail (g_date_valid_day (day));
975   
976   if (d->julian && !d->dmy) g_date_update_dmy(d);
977   d->julian = FALSE;
978   
979   d->day = day;
980   
981   if (g_date_valid_dmy (d->day, d->month, d->year))
982     d->dmy = TRUE;
983   else 
984     d->dmy = FALSE;
985 }
986
987 void         
988 g_date_set_year (GDate     *d, 
989                  GDateYear  y)
990 {
991   g_return_if_fail (d != NULL);
992   g_return_if_fail (g_date_valid_year (y));
993   
994   if (d->julian && !d->dmy) g_date_update_dmy(d);
995   d->julian = FALSE;
996   
997   d->year = y;
998   
999   if (g_date_valid_dmy (d->day, d->month, d->year))
1000     d->dmy = TRUE;
1001   else 
1002     d->dmy = FALSE;
1003 }
1004
1005 void         
1006 g_date_set_dmy (GDate      *d, 
1007                 GDateDay    day, 
1008                 GDateMonth  m, 
1009                 GDateYear   y)
1010 {
1011   g_return_if_fail (d != NULL);
1012   g_return_if_fail (g_date_valid_dmy (day, m, y));
1013   
1014   d->julian = FALSE;
1015   
1016   d->month = m;
1017   d->day   = day;
1018   d->year  = y;
1019   
1020   d->dmy = TRUE;
1021 }
1022
1023 void         
1024 g_date_set_julian (GDate   *d, 
1025                    guint32  j)
1026 {
1027   g_return_if_fail (d != NULL);
1028   g_return_if_fail (g_date_valid_julian (j));
1029   
1030   d->julian_days = j;
1031   d->julian = TRUE;
1032   d->dmy = FALSE;
1033 }
1034
1035
1036 gboolean     
1037 g_date_is_first_of_month (const GDate *d)
1038 {
1039   g_return_val_if_fail (g_date_valid (d), FALSE);
1040   
1041   if (!d->dmy) 
1042     g_date_update_dmy (d);
1043
1044   g_return_val_if_fail (d->dmy, FALSE);  
1045   
1046   if (d->day == 1) return TRUE;
1047   else return FALSE;
1048 }
1049
1050 gboolean     
1051 g_date_is_last_of_month (const GDate *d)
1052 {
1053   gint index;
1054   
1055   g_return_val_if_fail (g_date_valid (d), FALSE);
1056   
1057   if (!d->dmy) 
1058     g_date_update_dmy (d);
1059
1060   g_return_val_if_fail (d->dmy, FALSE);  
1061   
1062   index = g_date_is_leap_year (d->year) ? 1 : 0;
1063   
1064   if (d->day == days_in_months[index][d->month]) return TRUE;
1065   else return FALSE;
1066 }
1067
1068 void         
1069 g_date_add_days (GDate *d, 
1070                  guint  ndays)
1071 {
1072   g_return_if_fail (g_date_valid (d));
1073   
1074   if (!d->julian)
1075     g_date_update_julian (d);
1076
1077   g_return_if_fail (d->julian);
1078   
1079   d->julian_days += ndays;
1080   d->dmy = FALSE;
1081 }
1082
1083 void         
1084 g_date_subtract_days (GDate *d, 
1085                       guint  ndays)
1086 {
1087   g_return_if_fail (g_date_valid (d));
1088   
1089   if (!d->julian)
1090     g_date_update_julian (d);
1091
1092   g_return_if_fail (d->julian);
1093   g_return_if_fail (d->julian_days > ndays);
1094   
1095   d->julian_days -= ndays;
1096   d->dmy = FALSE;
1097 }
1098
1099 void         
1100 g_date_add_months (GDate *d, 
1101                    guint  nmonths)
1102 {
1103   guint years, months;
1104   gint index;
1105   
1106   g_return_if_fail (g_date_valid (d));
1107   
1108   if (!d->dmy) 
1109     g_date_update_dmy (d);
1110
1111   g_return_if_fail (d->dmy);  
1112   
1113   nmonths += d->month - 1;
1114   
1115   years  = nmonths/12;
1116   months = nmonths%12;
1117   
1118   d->month = months + 1;
1119   d->year  += years;
1120   
1121   index = g_date_is_leap_year (d->year) ? 1 : 0;
1122   
1123   if (d->day > days_in_months[index][d->month])
1124     d->day = days_in_months[index][d->month];
1125   
1126   d->julian = FALSE;
1127   
1128   g_return_if_fail (g_date_valid (d));
1129 }
1130
1131 void         
1132 g_date_subtract_months (GDate *d, 
1133                         guint  nmonths)
1134 {
1135   guint years, months;
1136   gint index;
1137   
1138   g_return_if_fail (g_date_valid (d));
1139   
1140   if (!d->dmy) 
1141     g_date_update_dmy (d);
1142
1143   g_return_if_fail (d->dmy);  
1144   
1145   years  = nmonths/12;
1146   months = nmonths%12;
1147   
1148   g_return_if_fail (d->year > years);
1149   
1150   d->year  -= years;
1151   
1152   if (d->month > months) d->month -= months;
1153   else 
1154     {
1155       months -= d->month;
1156       d->month = 12 - months;
1157       d->year -= 1;
1158     }
1159   
1160   index = g_date_is_leap_year (d->year) ? 1 : 0;
1161   
1162   if (d->day > days_in_months[index][d->month])
1163     d->day = days_in_months[index][d->month];
1164   
1165   d->julian = FALSE;
1166   
1167   g_return_if_fail (g_date_valid (d));
1168 }
1169
1170 void         
1171 g_date_add_years (GDate *d, 
1172                   guint  nyears)
1173 {
1174   g_return_if_fail (g_date_valid (d));
1175   
1176   if (!d->dmy) 
1177     g_date_update_dmy (d);
1178
1179   g_return_if_fail (d->dmy);  
1180   
1181   d->year += nyears;
1182   
1183   if (d->month == 2 && d->day == 29)
1184     {
1185       if (!g_date_is_leap_year (d->year))
1186         d->day = 28;
1187     }
1188   
1189   d->julian = FALSE;
1190 }
1191
1192 void         
1193 g_date_subtract_years (GDate *d, 
1194                        guint  nyears)
1195 {
1196   g_return_if_fail (g_date_valid (d));
1197   
1198   if (!d->dmy) 
1199     g_date_update_dmy (d);
1200
1201   g_return_if_fail (d->dmy);  
1202   g_return_if_fail (d->year > nyears);
1203   
1204   d->year -= nyears;
1205   
1206   if (d->month == 2 && d->day == 29)
1207     {
1208       if (!g_date_is_leap_year (d->year))
1209         d->day = 28;
1210     }
1211   
1212   d->julian = FALSE;
1213 }
1214
1215 gboolean     
1216 g_date_is_leap_year (GDateYear year)
1217 {
1218   g_return_val_if_fail (g_date_valid_year (year), FALSE);
1219   
1220   return ( (((year % 4) == 0) && ((year % 100) != 0)) ||
1221            (year % 400) == 0 );
1222 }
1223
1224 guint8         
1225 g_date_get_days_in_month (GDateMonth month, 
1226                           GDateYear  year)
1227 {
1228   gint index;
1229   
1230   g_return_val_if_fail (g_date_valid_year (year), 0);
1231   g_return_val_if_fail (g_date_valid_month (month), 0);
1232   
1233   index = g_date_is_leap_year (year) ? 1 : 0;
1234   
1235   return days_in_months[index][month];
1236 }
1237
1238 guint8       
1239 g_date_get_monday_weeks_in_year (GDateYear year)
1240 {
1241   GDate d;
1242   
1243   g_return_val_if_fail (g_date_valid_year (year), 0);
1244   
1245   g_date_clear (&d, 1);
1246   g_date_set_dmy (&d, 1, 1, year);
1247   if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1248   g_date_set_dmy (&d, 31, 12, year);
1249   if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1250   if (g_date_is_leap_year (year)) 
1251     {
1252       g_date_set_dmy (&d, 2, 1, year);
1253       if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1254       g_date_set_dmy (&d, 30, 12, year);
1255       if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1256     }
1257   return 52;
1258 }
1259
1260 guint8       
1261 g_date_get_sunday_weeks_in_year (GDateYear year)
1262 {
1263   GDate d;
1264   
1265   g_return_val_if_fail (g_date_valid_year (year), 0);
1266   
1267   g_date_clear (&d, 1);
1268   g_date_set_dmy (&d, 1, 1, year);
1269   if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1270   g_date_set_dmy (&d, 31, 12, year);
1271   if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1272   if (g_date_is_leap_year (year)) 
1273     {
1274       g_date_set_dmy (&d, 2, 1, year);
1275       if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1276       g_date_set_dmy (&d, 30, 12, year);
1277       if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1278     }
1279   return 52;
1280 }
1281
1282 gint         
1283 g_date_compare (const GDate *lhs, 
1284                 const GDate *rhs)
1285 {
1286   g_return_val_if_fail (lhs != NULL, 0);
1287   g_return_val_if_fail (rhs != NULL, 0);
1288   g_return_val_if_fail (g_date_valid (lhs), 0);
1289   g_return_val_if_fail (g_date_valid (rhs), 0);
1290   
1291   /* Remember the self-comparison case! I think it works right now. */
1292   
1293   while (TRUE)
1294     {
1295       if (lhs->julian && rhs->julian) 
1296         {
1297           if (lhs->julian_days < rhs->julian_days) return -1;
1298           else if (lhs->julian_days > rhs->julian_days) return 1;
1299           else                                          return 0;
1300         }
1301       else if (lhs->dmy && rhs->dmy) 
1302         {
1303           if (lhs->year < rhs->year)               return -1;
1304           else if (lhs->year > rhs->year)               return 1;
1305           else 
1306             {
1307               if (lhs->month < rhs->month)         return -1;
1308               else if (lhs->month > rhs->month)         return 1;
1309               else 
1310                 {
1311                   if (lhs->day < rhs->day)              return -1;
1312                   else if (lhs->day > rhs->day)              return 1;
1313                   else                                       return 0;
1314                 }
1315               
1316             }
1317           
1318         }
1319       else
1320         {
1321           if (!lhs->julian) g_date_update_julian (lhs);
1322           if (!rhs->julian) g_date_update_julian (rhs);
1323           g_return_val_if_fail (lhs->julian, 0);
1324           g_return_val_if_fail (rhs->julian, 0);
1325         }
1326       
1327     }
1328   return 0; /* warnings */
1329 }
1330
1331
1332 void        
1333 g_date_to_struct_tm (const GDate *d, 
1334                      struct tm   *tm)
1335 {
1336   GDateWeekday day;
1337      
1338   g_return_if_fail (g_date_valid (d));
1339   g_return_if_fail (tm != NULL);
1340   
1341   if (!d->dmy) 
1342     g_date_update_dmy (d);
1343
1344   g_return_if_fail (d->dmy);
1345   
1346   /* zero all the irrelevant fields to be sure they're valid */
1347   
1348   /* On Linux and maybe other systems, there are weird non-POSIX
1349    * fields on the end of struct tm that choke strftime if they
1350    * contain garbage.  So we need to 0 the entire struct, not just the
1351    * fields we know to exist. 
1352    */
1353   
1354   memset (tm, 0x0, sizeof (struct tm));
1355   
1356   tm->tm_mday = d->day;
1357   tm->tm_mon  = d->month - 1; /* 0-11 goes in tm */
1358   tm->tm_year = ((int)d->year) - 1900; /* X/Open says tm_year can be negative */
1359   
1360   day = g_date_get_weekday (d);
1361   if (day == 7) day = 0; /* struct tm wants days since Sunday, so Sunday is 0 */
1362   
1363   tm->tm_wday = (int)day;
1364   
1365   tm->tm_yday = g_date_get_day_of_year (d) - 1; /* 0 to 365 */
1366   tm->tm_isdst = -1; /* -1 means "information not available" */
1367 }
1368
1369 void
1370 g_date_clamp (GDate       *date,
1371               const GDate *min_date,
1372               const GDate *max_date)
1373 {
1374   g_return_if_fail (g_date_valid (date));
1375
1376   if (min_date != NULL)
1377     g_return_if_fail (g_date_valid (min_date));
1378
1379   if (max_date != NULL)
1380     g_return_if_fail (g_date_valid (max_date));
1381
1382   if (min_date != NULL && max_date != NULL)
1383     g_return_if_fail (g_date_compare (min_date, max_date) <= 0);
1384
1385   if (min_date && g_date_compare (date, min_date) < 0)
1386     *date = *min_date;
1387
1388   if (max_date && g_date_compare (max_date, date) < 0)
1389     *date = *max_date;
1390 }
1391
1392 void
1393 g_date_order (GDate *date1,
1394               GDate *date2)
1395 {
1396   g_return_if_fail (g_date_valid (date1));
1397   g_return_if_fail (g_date_valid (date2));
1398
1399   if (g_date_compare (date1, date2) > 0)
1400     {
1401       GDate tmp = *date1;
1402       *date1 = *date2;
1403       *date2 = tmp;
1404     }
1405 }
1406
1407 #ifdef G_OS_WIN32
1408 static gsize
1409 win32_strftime_helper (const GDate     *d,
1410                        const gchar     *format,
1411                        const struct tm *tm,
1412                        gchar           *s,
1413                        gsize            slen)
1414 {
1415   SYSTEMTIME systemtime;
1416   TIME_ZONE_INFORMATION tzinfo;
1417   LCID lcid;
1418   int n, k;
1419   GArray *result;
1420   const gchar *p;
1421   gunichar c;
1422   const wchar_t digits[] = L"0123456789";
1423   gchar *convbuf;
1424   glong convlen = 0;
1425   gsize retval;
1426
1427   systemtime.wYear = tm->tm_year + 1900;
1428   systemtime.wMonth = tm->tm_mon + 1;
1429   systemtime.wDayOfWeek = tm->tm_wday;
1430   systemtime.wDay = tm->tm_mday;
1431   systemtime.wHour = tm->tm_hour;
1432   systemtime.wMinute = tm->tm_min;
1433   systemtime.wSecond = tm->tm_sec;
1434   systemtime.wMilliseconds = 0;
1435   
1436   lcid = GetThreadLocale ();
1437   result = g_array_sized_new (FALSE, FALSE, sizeof (wchar_t), MAX (128, strlen (format) * 2));
1438
1439   p = format;
1440   while (*p)
1441     {
1442       c = g_utf8_get_char (p);
1443       if (c == '%')
1444         {
1445           p = g_utf8_next_char (p);
1446           if (!*p)
1447             {
1448               s[0] = '\0';
1449               g_array_free (result, TRUE);
1450
1451               return 0;
1452             }
1453           
1454           c = g_utf8_get_char (p);
1455           if (c == 'E' || c == 'O')
1456             {
1457               /* Ignore modified conversion specifiers for now. */
1458               p = g_utf8_next_char (p);
1459               if (!*p)
1460                 {
1461                   s[0] = '\0';
1462                   g_array_free (result, TRUE);
1463                   
1464                   return 0;
1465                 }
1466
1467               c = g_utf8_get_char (p);
1468             }
1469
1470           switch (c)
1471             {
1472             case 'a':
1473               if (systemtime.wDayOfWeek == 0)
1474                 k = 6;
1475               else
1476                 k = systemtime.wDayOfWeek - 1;
1477               n = GetLocaleInfoW (lcid, LOCALE_SABBREVDAYNAME1+k, NULL, 0);
1478               g_array_set_size (result, result->len + n);
1479               GetLocaleInfoW (lcid, LOCALE_SABBREVDAYNAME1+k, ((wchar_t *) result->data) + result->len - n, n);
1480               g_array_set_size (result, result->len - 1);
1481               break;
1482             case 'A':
1483               if (systemtime.wDayOfWeek == 0)
1484                 k = 6;
1485               else
1486                 k = systemtime.wDayOfWeek - 1;
1487               n = GetLocaleInfoW (lcid, LOCALE_SDAYNAME1+k, NULL, 0);
1488               g_array_set_size (result, result->len + n);
1489               GetLocaleInfoW (lcid, LOCALE_SDAYNAME1+k, ((wchar_t *) result->data) + result->len - n, n);
1490               g_array_set_size (result, result->len - 1);
1491               break;
1492             case 'b':
1493             case 'h':
1494               n = GetLocaleInfoW (lcid, LOCALE_SABBREVMONTHNAME1+systemtime.wMonth-1, NULL, 0);
1495               g_array_set_size (result, result->len + n);
1496               GetLocaleInfoW (lcid, LOCALE_SABBREVMONTHNAME1+systemtime.wMonth-1, ((wchar_t *) result->data) + result->len - n, n);
1497               g_array_set_size (result, result->len - 1);
1498               break;
1499             case 'B':
1500               n = GetLocaleInfoW (lcid, LOCALE_SMONTHNAME1+systemtime.wMonth-1, NULL, 0);
1501               g_array_set_size (result, result->len + n);
1502               GetLocaleInfoW (lcid, LOCALE_SMONTHNAME1+systemtime.wMonth-1, ((wchar_t *) result->data) + result->len - n, n);
1503               g_array_set_size (result, result->len - 1);
1504               break;
1505             case 'c':
1506               n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
1507               if (n > 0)
1508                 {
1509                   g_array_set_size (result, result->len + n);
1510                   GetDateFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
1511                   g_array_set_size (result, result->len - 1);
1512                 }
1513               g_array_append_vals (result, L" ", 1);
1514               n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
1515               if (n > 0)
1516                 {
1517                   g_array_set_size (result, result->len + n);
1518                   GetTimeFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
1519                   g_array_set_size (result, result->len - 1);
1520                 }
1521               break;
1522             case 'C':
1523               g_array_append_vals (result, digits + systemtime.wYear/1000, 1);
1524               g_array_append_vals (result, digits + (systemtime.wYear/1000)%10, 1);
1525               break;
1526             case 'd':
1527               g_array_append_vals (result, digits + systemtime.wDay/10, 1);
1528               g_array_append_vals (result, digits + systemtime.wDay%10, 1);
1529               break;
1530             case 'D':
1531               g_array_append_vals (result, digits + systemtime.wMonth/10, 1);
1532               g_array_append_vals (result, digits + systemtime.wMonth%10, 1);
1533               g_array_append_vals (result, L"/", 1);
1534               g_array_append_vals (result, digits + systemtime.wDay/10, 1);
1535               g_array_append_vals (result, digits + systemtime.wDay%10, 1);
1536               g_array_append_vals (result, L"/", 1);
1537               g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
1538               g_array_append_vals (result, digits + systemtime.wYear%10, 1);
1539               break;
1540             case 'e':
1541               if (systemtime.wDay >= 10)
1542                 g_array_append_vals (result, digits + systemtime.wDay/10, 1);
1543               else
1544                 g_array_append_vals (result, L" ", 1);
1545               g_array_append_vals (result, digits + systemtime.wDay%10, 1);
1546               break;
1547
1548               /* A GDate has no time fields, so for now we can
1549                * hardcode all time conversions into zeros (or 12 for
1550                * %I). The alternative code snippets in the #else
1551                * branches are here ready to be taken into use when
1552                * needed by a g_strftime() or g_date_and_time_format()
1553                * or whatever.
1554                */
1555             case 'H':
1556 #if 1
1557               g_array_append_vals (result, L"00", 2);
1558 #else
1559               g_array_append_vals (result, digits + systemtime.wHour/10, 1);
1560               g_array_append_vals (result, digits + systemtime.wHour%10, 1);
1561 #endif
1562               break;
1563             case 'I':
1564 #if 1
1565               g_array_append_vals (result, L"12", 2);
1566 #else
1567               if (systemtime.wHour == 0)
1568                 g_array_append_vals (result, L"12", 2);
1569               else
1570                 {
1571                   g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
1572                   g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
1573                 }
1574 #endif
1575               break;
1576             case  'j':
1577               g_array_append_vals (result, digits + (tm->tm_yday+1)/100, 1);
1578               g_array_append_vals (result, digits + ((tm->tm_yday+1)/10)%10, 1);
1579               g_array_append_vals (result, digits + (tm->tm_yday+1)%10, 1);
1580               break;
1581             case 'm':
1582               g_array_append_vals (result, digits + systemtime.wMonth/10, 1);
1583               g_array_append_vals (result, digits + systemtime.wMonth%10, 1);
1584               break;
1585             case 'M':
1586 #if 1
1587               g_array_append_vals (result, L"00", 2);
1588 #else
1589               g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
1590               g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
1591 #endif
1592               break;
1593             case 'n':
1594               g_array_append_vals (result, L"\n", 1);
1595               break;
1596             case 'p':
1597               n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
1598               if (n > 0)
1599                 {
1600                   g_array_set_size (result, result->len + n);
1601                   GetTimeFormatW (lcid, 0, &systemtime, L"tt", ((wchar_t *) result->data) + result->len - n, n);
1602                   g_array_set_size (result, result->len - 1);
1603                 }
1604               break;
1605             case 'r':
1606               /* This is a rather odd format. Hard to say what to do.
1607                * Let's always use the POSIX %I:%M:%S %p
1608                */
1609 #if 1
1610               g_array_append_vals (result, L"12:00:00", 8);
1611 #else
1612               if (systemtime.wHour == 0)
1613                 g_array_append_vals (result, L"12", 2);
1614               else
1615                 {
1616                   g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
1617                   g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
1618                 }
1619               g_array_append_vals (result, L":", 1);
1620               g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
1621               g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
1622               g_array_append_vals (result, L":", 1);
1623               g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
1624               g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
1625               g_array_append_vals (result, L" ", 1);
1626 #endif
1627               n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
1628               if (n > 0)
1629                 {
1630                   g_array_set_size (result, result->len + n);
1631                   GetTimeFormatW (lcid, 0, &systemtime, L"tt", ((wchar_t *) result->data) + result->len - n, n);
1632                   g_array_set_size (result, result->len - 1);
1633                 }
1634               break;
1635             case 'R':
1636 #if 1
1637               g_array_append_vals (result, L"00:00", 5);
1638 #else
1639               g_array_append_vals (result, digits + systemtime.wHour/10, 1);
1640               g_array_append_vals (result, digits + systemtime.wHour%10, 1);
1641               g_array_append_vals (result, L":", 1);
1642               g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
1643               g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
1644 #endif
1645               break;
1646             case 'S':
1647 #if 1
1648               g_array_append_vals (result, L"00", 2);
1649 #else
1650               g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
1651               g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
1652 #endif
1653               break;
1654             case 't':
1655               g_array_append_vals (result, L"\t", 1);
1656               break;
1657             case 'T':
1658 #if 1
1659               g_array_append_vals (result, L"00:00:00", 8);
1660 #else
1661               g_array_append_vals (result, digits + systemtime.wHour/10, 1);
1662               g_array_append_vals (result, digits + systemtime.wHour%10, 1);
1663               g_array_append_vals (result, L":", 1);
1664               g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
1665               g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
1666               g_array_append_vals (result, L":", 1);
1667               g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
1668               g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
1669 #endif
1670               break;
1671             case 'u':
1672               if (systemtime.wDayOfWeek == 0)
1673                 g_array_append_vals (result, L"7", 1);
1674               else
1675                 g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
1676               break;
1677             case 'U':
1678               n = g_date_get_sunday_week_of_year (d);
1679               g_array_append_vals (result, digits + n/10, 1);
1680               g_array_append_vals (result, digits + n%10, 1);
1681               break;
1682             case 'V':
1683               n = g_date_get_iso8601_week_of_year (d);
1684               g_array_append_vals (result, digits + n/10, 1);
1685               g_array_append_vals (result, digits + n%10, 1);
1686               break;
1687             case 'w':
1688               g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
1689               break;
1690             case 'W':
1691               n = g_date_get_monday_week_of_year (d);
1692               g_array_append_vals (result, digits + n/10, 1);
1693               g_array_append_vals (result, digits + n%10, 1);
1694               break;
1695             case 'x':
1696               n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
1697               if (n > 0)
1698                 {
1699                   g_array_set_size (result, result->len + n);
1700                   GetDateFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
1701                   g_array_set_size (result, result->len - 1);
1702                 }
1703               break;
1704             case 'X':
1705               n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
1706               if (n > 0)
1707                 {
1708                   g_array_set_size (result, result->len + n);
1709                   GetTimeFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
1710                   g_array_set_size (result, result->len - 1);
1711                 }
1712               break;
1713             case 'y':
1714               g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
1715               g_array_append_vals (result, digits + systemtime.wYear%10, 1);
1716               break;
1717             case 'Y':
1718               g_array_append_vals (result, digits + systemtime.wYear/1000, 1);
1719               g_array_append_vals (result, digits + (systemtime.wYear/100)%10, 1);
1720               g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
1721               g_array_append_vals (result, digits + systemtime.wYear%10, 1);
1722               break;
1723             case 'Z':
1724               n = GetTimeZoneInformation (&tzinfo);
1725               if (n == TIME_ZONE_ID_UNKNOWN)
1726                 ;
1727               else if (n == TIME_ZONE_ID_STANDARD)
1728                 g_array_append_vals (result, tzinfo.StandardName, wcslen (tzinfo.StandardName));
1729               else if (n == TIME_ZONE_ID_DAYLIGHT)
1730                 g_array_append_vals (result, tzinfo.DaylightName, wcslen (tzinfo.DaylightName));
1731               break;
1732             case '%':
1733               g_array_append_vals (result, L"%", 1);
1734               break;
1735             }      
1736         } 
1737       else if (c <= 0xFFFF)
1738         {
1739           wchar_t wc = c;
1740           g_array_append_vals (result, &wc, 1);
1741         }
1742       else
1743         {
1744           glong nwc;
1745           wchar_t *ws;
1746
1747           ws = g_ucs4_to_utf16 (&c, 1, NULL, &nwc, NULL);
1748           g_array_append_vals (result, ws, nwc);
1749           g_free (ws);
1750         }
1751       p = g_utf8_next_char (p);
1752     }
1753   
1754   convbuf = g_utf16_to_utf8 ((wchar_t *) result->data, result->len, NULL, &convlen, NULL);
1755   g_array_free (result, TRUE);
1756
1757   if (!convbuf)
1758     {
1759       s[0] = '\0';
1760       return 0;
1761     }
1762   
1763   if (slen <= convlen)
1764     {
1765       /* Ensure only whole characters are copied into the buffer. */
1766       gchar *end = g_utf8_find_prev_char (convbuf, convbuf + slen);
1767       g_assert (end != NULL);
1768       convlen = end - convbuf;
1769
1770       /* Return 0 because the buffer isn't large enough. */
1771       retval = 0;
1772     }
1773   else
1774     retval = convlen;
1775
1776   memcpy (s, convbuf, convlen);
1777   s[convlen] = '\0';
1778   g_free (convbuf);
1779
1780   return retval;
1781 }
1782
1783 #endif
1784
1785 gsize     
1786 g_date_strftime (gchar       *s, 
1787                  gsize        slen, 
1788                  const gchar *format, 
1789                  const GDate *d)
1790 {
1791   struct tm tm;
1792 #ifndef G_OS_WIN32
1793   gsize locale_format_len = 0;
1794   gchar *locale_format;
1795   gsize tmplen;
1796   gchar *tmpbuf;
1797   gsize tmpbufsize;
1798   gsize convlen = 0;
1799   gchar *convbuf;
1800   GError *error = NULL;
1801   gsize retval;
1802 #endif
1803
1804   g_return_val_if_fail (g_date_valid (d), 0);
1805   g_return_val_if_fail (slen > 0, 0); 
1806   g_return_val_if_fail (format != NULL, 0);
1807   g_return_val_if_fail (s != NULL, 0);
1808
1809   g_date_to_struct_tm (d, &tm);
1810
1811 #ifdef G_OS_WIN32
1812   if (!g_utf8_validate (format, -1, NULL))
1813     {
1814       s[0] = '\0';
1815       return 0;
1816     }
1817   return win32_strftime_helper (d, format, &tm, s, slen);
1818 #else
1819
1820   locale_format = g_locale_from_utf8 (format, -1, NULL, &locale_format_len, &error);
1821
1822   if (error)
1823     {
1824       g_warning (G_STRLOC "Error converting format to locale encoding: %s\n", error->message);
1825       g_error_free (error);
1826
1827       s[0] = '\0';
1828       return 0;
1829     }
1830
1831   tmpbufsize = MAX (128, locale_format_len * 2);
1832   while (TRUE)
1833     {
1834       tmpbuf = g_malloc (tmpbufsize);
1835
1836       /* Set the first byte to something other than '\0', to be able to
1837        * recognize whether strftime actually failed or just returned "".
1838        */
1839       tmpbuf[0] = '\1';
1840       tmplen = strftime (tmpbuf, tmpbufsize, locale_format, &tm);
1841
1842       if (tmplen == 0 && tmpbuf[0] != '\0')
1843         {
1844           g_free (tmpbuf);
1845           tmpbufsize *= 2;
1846
1847           if (tmpbufsize > 65536)
1848             {
1849               g_warning (G_STRLOC "Maximum buffer size for g_date_strftime exceeded: giving up\n");
1850               g_free (locale_format);
1851
1852               s[0] = '\0';
1853               return 0;
1854             }
1855         }
1856       else
1857         break;
1858     }
1859   g_free (locale_format);
1860
1861   convbuf = g_locale_to_utf8 (tmpbuf, tmplen, NULL, &convlen, &error);
1862   g_free (tmpbuf);
1863
1864   if (error)
1865     {
1866       g_warning (G_STRLOC "Error converting results of strftime to UTF-8: %s\n", error->message);
1867       g_error_free (error);
1868
1869       s[0] = '\0';
1870       return 0;
1871     }
1872
1873   if (slen <= convlen)
1874     {
1875       /* Ensure only whole characters are copied into the buffer.
1876        */
1877       gchar *end = g_utf8_find_prev_char (convbuf, convbuf + slen);
1878       g_assert (end != NULL);
1879       convlen = end - convbuf;
1880
1881       /* Return 0 because the buffer isn't large enough.
1882        */
1883       retval = 0;
1884     }
1885   else
1886     retval = convlen;
1887
1888   memcpy (s, convbuf, convlen);
1889   s[convlen] = '\0';
1890   g_free (convbuf);
1891
1892   return retval;
1893 #endif
1894 }
1895
1896 #define __G_DATE_C__
1897 #include "galiasdef.c"
1898