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