315f7a336fbfeb798de75d6236ff1e571acffbf3
[platform/upstream/glib.git] / glib / gdate.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 /* 
28  * MT safe
29  */
30
31 #include "config.h"
32 #include "glibconfig.h"
33
34 #define DEBUG_MSG(x)    /* */
35 #ifdef G_ENABLE_DEBUG
36 /* #define DEBUG_MSG(args)      g_message args ; */
37 #endif
38
39 #include <time.h>
40 #include <string.h>
41 #include <stdlib.h>
42 #include <locale.h>
43
44 #ifdef G_OS_WIN32
45 #include <windows.h>
46 #endif
47
48 #include "gdate.h"
49
50 #include "gconvert.h"
51 #include "gmem.h"
52 #include "gstrfuncs.h"
53 #include "gtestutils.h"
54 #include "gthread.h"
55 #include "gunicode.h"
56
57 #ifdef G_OS_WIN32
58 #include "garray.h"
59 #endif
60
61 /**
62  * SECTION:date
63  * @title: Date and Time Functions
64  * @short_description: calendrical calculations and miscellaneous time stuff
65  *
66  * The #GDate data structure represents a day between January 1, Year 1,
67  * and sometime a few thousand years in the future (right now it will go
68  * to the year 65535 or so, but g_date_set_parse() only parses up to the
69  * year 8000 or so - just count on "a few thousand"). #GDate is meant to
70  * represent everyday dates, not astronomical dates or historical dates
71  * or ISO timestamps or the like. It extrapolates the current Gregorian
72  * calendar forward and backward in time; there is no attempt to change
73  * the calendar to match time periods or locations. #GDate does not store
74  * time information; it represents a <emphasis>day</emphasis>.
75  *
76  * The #GDate implementation has several nice features; it is only a
77  * 64-bit struct, so storing large numbers of dates is very efficient. It
78  * can keep both a Julian and day-month-year representation of the date,
79  * since some calculations are much easier with one representation or the
80  * other. A Julian representation is simply a count of days since some
81  * fixed day in the past; for #GDate the fixed day is January 1, 1 AD.
82  * ("Julian" dates in the #GDate API aren't really Julian dates in the
83  * technical sense; technically, Julian dates count from the start of the
84  * Julian period, Jan 1, 4713 BC).
85  *
86  * #GDate is simple to use. First you need a "blank" date; you can get a
87  * dynamically allocated date from g_date_new(), or you can declare an
88  * automatic variable or array and initialize it to a sane state by
89  * calling g_date_clear(). A cleared date is sane; it's safe to call
90  * g_date_set_dmy() and the other mutator functions to initialize the
91  * value of a cleared date. However, a cleared date is initially
92  * <emphasis>invalid</emphasis>, meaning that it doesn't represent a day
93  * that exists. It is undefined to call any of the date calculation
94  * routines on an invalid date. If you obtain a date from a user or other
95  * unpredictable source, you should check its validity with the
96  * g_date_valid() predicate. g_date_valid() is also used to check for
97  * errors with g_date_set_parse() and other functions that can
98  * fail. Dates can be invalidated by calling g_date_clear() again.
99  *
100  * <emphasis>It is very important to use the API to access the #GDate
101  * struct.</emphasis> Often only the day-month-year or only the Julian
102  * representation is valid. Sometimes neither is valid. Use the API.
103  *
104  * GLib also features #GDateTime which represents a precise time.
105  */
106
107 /**
108  * G_USEC_PER_SEC:
109  *
110  * Number of microseconds in one second (1 million).
111  * This macro is provided for code readability.
112  */
113
114 /**
115  * GTimeVal:
116  * @tv_sec: seconds
117  * @tv_usec: microseconds
118  *
119  * Represents a precise time, with seconds and microseconds.
120  * Similar to the <structname>struct timeval</structname> returned by
121  * the gettimeofday() UNIX system call.
122  *
123  * GLib is attempting to unify around the use of 64bit integers to
124  * represent microsecond-precision time. As such, this type will be
125  * removed from a future version of GLib.
126  */
127
128 /**
129  * GDate:
130  * @julian_days: the Julian representation of the date
131  * @julian: this bit is set if @julian_days is valid
132  * @dmy: this is set if @day, @month and @year are valid
133  * @day: the day of the day-month-year representation of the date,
134  *     as a number between 1 and 31
135  * @month: the day of the day-month-year representation of the date,
136  *     as a number between 1 and 12
137  * @year: the day of the day-month-year representation of the date
138  *
139  * Represents a day between January 1, Year 1 and a few thousand years in
140  * the future. None of its members should be accessed directly. If the
141  * <structname>GDate</structname> is obtained from g_date_new(), it will
142  * be safe to mutate but invalid and thus not safe for calendrical
143  * computations. If it's declared on the stack, it will contain garbage
144  * so must be initialized with g_date_clear(). g_date_clear() makes the
145  * date invalid but sane. An invalid date doesn't represent a day, it's
146  * "empty." A date becomes valid after you set it to a Julian day or you
147  * set a day, month, and year.
148  */
149
150 /**
151  * GTime:
152  * Simply a replacement for <type>time_t</type>. It has been deprecated
153  * since it is <emphasis>not</emphasis> equivalent to <type>time_t</type>
154  * on 64-bit platforms with a 64-bit <type>time_t</type>.
155  * Unrelated to #GTimer.
156  *
157  * Note that <type>GTime</type> is defined to always be a 32bit integer,
158  * unlike <type>time_t</type> which may be 64bit on some systems.
159  * Therefore, <type>GTime</type> will overflow in the year 2038, and
160  * you cannot use the address of a <type>GTime</type> variable as argument
161  * to the UNIX time() function. Instead, do the following:
162  * |[
163  * time_t ttime;
164  * GTime gtime;
165  *
166  * time (&amp;ttime);
167  * gtime = (GTime)ttime;
168  * ]|
169  */
170
171 /**
172  * GDateDMY:
173  * @G_DATE_DAY: a day
174  * @G_DATE_MONTH: a month
175  * @G_DATE_YEAR: a year
176  *
177  * This enumeration isn't used in the API, but may be useful if you need
178  * to mark a number as a day, month, or year.
179  */
180
181 /**
182  * GDateDay:
183  *
184  * Integer representing a day of the month; between 1 and
185  * 31. #G_DATE_BAD_DAY represents an invalid day of the month.
186  */
187
188 /**
189  * GDateMonth:
190  * @G_DATE_BAD_MONTH: invalid value
191  * @G_DATE_JANUARY: January
192  * @G_DATE_FEBRUARY: February
193  * @G_DATE_MARCH: March
194  * @G_DATE_APRIL: April
195  * @G_DATE_MAY: May
196  * @G_DATE_JUNE: June
197  * @G_DATE_JULY: July
198  * @G_DATE_AUGUST: August
199  * @G_DATE_SEPTEMBER: September
200  * @G_DATE_OCTOBER: October
201  * @G_DATE_NOVEMBER: November
202  * @G_DATE_DECEMBER: December
203  *
204  * Enumeration representing a month; values are #G_DATE_JANUARY,
205  * #G_DATE_FEBRUARY, etc. #G_DATE_BAD_MONTH is the invalid value.
206  */
207
208 /**
209  * GDateYear:
210  *
211  * Integer representing a year; #G_DATE_BAD_YEAR is the invalid
212  * value. The year must be 1 or higher; negative (BC) years are not
213  * allowed. The year is represented with four digits.
214  */
215
216 /**
217  * GDateWeekday:
218  * @G_DATE_BAD_WEEKDAY: invalid value
219  * @G_DATE_MONDAY: Monday
220  * @G_DATE_TUESDAY: Tuesday
221  * @G_DATE_WEDNESDAY: Wednesday
222  * @G_DATE_THURSDAY: Thursday
223  * @G_DATE_FRIDAY: Friday
224  * @G_DATE_SATURDAY: Saturday
225  * @G_DATE_SUNDAY: Sunday
226  *
227  * Enumeration representing a day of the week; #G_DATE_MONDAY,
228  * #G_DATE_TUESDAY, etc. #G_DATE_BAD_WEEKDAY is an invalid weekday.
229  */
230
231 /**
232  * G_DATE_BAD_DAY:
233  *
234  * Represents an invalid #GDateDay.
235  */
236
237 /**
238  * G_DATE_BAD_JULIAN:
239  *
240  * Represents an invalid Julian day number.
241  */
242
243 /**
244  * G_DATE_BAD_YEAR:
245  *
246  * Represents an invalid year.
247  */
248
249 /**
250  * g_date_new:
251  *
252  * Allocates a #GDate and initializes
253  * it to a sane state. The new date will
254  * be cleared (as if you'd called g_date_clear()) but invalid (it won't
255  * represent an existing day). Free the return value with g_date_free().
256  *
257  * Returns: a newly-allocated #GDate
258  */
259 GDate*
260 g_date_new (void)
261 {
262   GDate *d = g_new0 (GDate, 1); /* happily, 0 is the invalid flag for everything. */
263   
264   return d;
265 }
266
267 /**
268  * g_date_new_dmy:
269  * @day: day of the month
270  * @month: month of the year
271  * @year: year
272  *
273  * Like g_date_new(), but also sets the value of the date. Assuming the
274  * day-month-year triplet you pass in represents an existing day, the
275  * returned date will be valid.
276  *
277  * Returns: a newly-allocated #GDate initialized with @day, @month, and @year
278  */
279 GDate*
280 g_date_new_dmy (GDateDay   day, 
281                 GDateMonth m, 
282                 GDateYear  y)
283 {
284   GDate *d;
285   g_return_val_if_fail (g_date_valid_dmy (day, m, y), NULL);
286   
287   d = g_new (GDate, 1);
288   
289   d->julian = FALSE;
290   d->dmy    = TRUE;
291   
292   d->month = m;
293   d->day   = day;
294   d->year  = y;
295   
296   g_assert (g_date_valid (d));
297   
298   return d;
299 }
300
301 /**
302  * g_date_new_julian:
303  * julian_day: days since January 1, Year 1
304  *
305  * Like g_date_new(), but also sets the value of the date. Assuming the
306  * Julian day number you pass in is valid (greater than 0, less than an
307  * unreasonably large number), the returned date will be valid.
308  *
309  * Returns: a newly-allocated #GDate initialized with @julian_day
310  */
311 GDate*
312 g_date_new_julian (guint32 j)
313 {
314   GDate *d;
315   g_return_val_if_fail (g_date_valid_julian (j), NULL);
316   
317   d = g_new (GDate, 1);
318   
319   d->julian = TRUE;
320   d->dmy    = FALSE;
321   
322   d->julian_days = j;
323   
324   g_assert (g_date_valid (d));
325   
326   return d;
327 }
328
329 /**
330  * g_date_free:
331  *
332  * Frees a #GDate returned from g_date_new().
333  */
334 void
335 g_date_free (GDate *d)
336 {
337   g_return_if_fail (d != NULL);
338   
339   g_free (d);
340 }
341
342 /**
343  * g_date_valid:
344  * @date: a #GDate to check
345  *
346  * Returns %TRUE if the #GDate represents an existing day. The date must not
347  * contain garbage; it should have been initialized with g_date_clear()
348  * if it wasn't allocated by one of the g_date_new() variants.
349  *
350  * Returns: Whether the date is valid
351  */
352 gboolean     
353 g_date_valid (const GDate *d)
354 {
355   g_return_val_if_fail (d != NULL, FALSE);
356   
357   return (d->julian || d->dmy);
358 }
359
360 static const guint8 days_in_months[2][13] = 
361 {  /* error, jan feb mar apr may jun jul aug sep oct nov dec */
362   {  0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, 
363   {  0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } /* leap year */
364 };
365
366 static const guint16 days_in_year[2][14] = 
367 {  /* 0, jan feb mar apr may  jun  jul  aug  sep  oct  nov  dec */
368   {  0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, 
369   {  0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
370 };
371
372 /**
373  * g_date_valid_month:
374  * @month: month
375  *
376  * Returns %TRUE if the month value is valid. The 12 #GDateMonth
377  * enumeration values are the only valid months.
378  *
379  * Returns: %TRUE if the month is valid
380  */
381 gboolean     
382 g_date_valid_month (GDateMonth m)
383
384   return ( (m > G_DATE_BAD_MONTH) && (m < 13) );
385 }
386
387 /**
388  * g_date_valid_year:
389  * @year: year
390  *
391  * Returns %TRUE if the year is valid. Any year greater than 0 is valid,
392  * though there is a 16-bit limit to what #GDate will understand.
393  *
394  * Returns: %TRUE if the year is valid
395  */
396 gboolean     
397 g_date_valid_year (GDateYear y)
398 {
399   return ( y > G_DATE_BAD_YEAR );
400 }
401
402 /**
403  * g_date_valid_day:
404  * @day: day to check
405  *
406  * Returns %TRUE if the day of the month is valid (a day is valid if it's
407  * between 1 and 31 inclusive).
408  *
409  * Returns: %TRUE if the day is valid
410  */
411
412 gboolean     
413 g_date_valid_day (GDateDay d)
414 {
415   return ( (d > G_DATE_BAD_DAY) && (d < 32) );
416 }
417
418 /**
419  * g_date_valid_weekday:
420  * @weekday: weekday
421  *
422  * Returns %TRUE if the weekday is valid. The seven #GDateWeekday enumeration
423  * values are the only valid weekdays.
424  *
425  * Returns: %TRUE if the weekday is valid
426  */
427 gboolean     
428 g_date_valid_weekday (GDateWeekday w)
429 {
430   return ( (w > G_DATE_BAD_WEEKDAY) && (w < 8) );
431 }
432
433 /**
434  * g_date_valid_julian:
435  * @julian_date: Julian day to check
436  *
437  * Returns %TRUE if the Julian day is valid. Anything greater than zero
438  * is basically a valid Julian, though there is a 32-bit limit.
439  *
440  * Returns: %TRUE if the Julian day is valid
441  */
442 gboolean     
443 g_date_valid_julian (guint32 j)
444 {
445   return (j > G_DATE_BAD_JULIAN);
446 }
447
448 /**
449  * g_date_valid_dmy:
450  * @day: day
451  * @month: month
452  * @year: year
453  *
454  * Returns %TRUE if the day-month-year triplet forms a valid, existing day
455  * in the range of days #GDate understands (Year 1 or later, no more than
456  * a few thousand years in the future).
457  *
458  * Returns: %TRUE if the date is a valid one
459  */
460 gboolean     
461 g_date_valid_dmy (GDateDay   d, 
462                   GDateMonth m, 
463                   GDateYear  y)
464 {
465   return ( (m > G_DATE_BAD_MONTH) &&
466            (m < 13)               && 
467            (d > G_DATE_BAD_DAY)   && 
468            (y > G_DATE_BAD_YEAR)  &&   /* must check before using g_date_is_leap_year */
469            (d <=  (g_date_is_leap_year (y) ? 
470                    days_in_months[1][m] : days_in_months[0][m])) );
471 }
472
473
474 /* "Julian days" just means an absolute number of days, where Day 1 ==
475  *   Jan 1, Year 1
476  */
477 static void
478 g_date_update_julian (const GDate *const_d)
479 {
480   GDate *d = (GDate *) const_d;
481   GDateYear year;
482   gint idx;
483   
484   g_return_if_fail (d != NULL);
485   g_return_if_fail (d->dmy);
486   g_return_if_fail (!d->julian);
487   g_return_if_fail (g_date_valid_dmy (d->day, d->month, d->year));
488   
489   /* What we actually do is: multiply years * 365 days in the year,
490    * add the number of years divided by 4, subtract the number of
491    * years divided by 100 and add the number of years divided by 400,
492    * which accounts for leap year stuff. Code from Steffen Beyer's
493    * DateCalc. 
494    */
495   
496   year = d->year - 1; /* we know d->year > 0 since it's valid */
497   
498   d->julian_days = year * 365U;
499   d->julian_days += (year >>= 2); /* divide by 4 and add */
500   d->julian_days -= (year /= 25); /* divides original # years by 100 */
501   d->julian_days += year >> 2;    /* divides by 4, which divides original by 400 */
502   
503   idx = g_date_is_leap_year (d->year) ? 1 : 0;
504   
505   d->julian_days += days_in_year[idx][d->month] + d->day;
506   
507   g_return_if_fail (g_date_valid_julian (d->julian_days));
508   
509   d->julian = TRUE;
510 }
511
512 static void 
513 g_date_update_dmy (const GDate *const_d)
514 {
515   GDate *d = (GDate *) const_d;
516   GDateYear y;
517   GDateMonth m;
518   GDateDay day;
519   
520   guint32 A, B, C, D, E, M;
521   
522   g_return_if_fail (d != NULL);
523   g_return_if_fail (d->julian);
524   g_return_if_fail (!d->dmy);
525   g_return_if_fail (g_date_valid_julian (d->julian_days));
526   
527   /* Formula taken from the Calendar FAQ; the formula was for the
528    *  Julian Period which starts on 1 January 4713 BC, so we add
529    *  1,721,425 to the number of days before doing the formula.
530    *
531    * I'm sure this can be simplified for our 1 January 1 AD period
532    * start, but I can't figure out how to unpack the formula.  
533    */
534   
535   A = d->julian_days + 1721425 + 32045;
536   B = ( 4 *(A + 36524) )/ 146097 - 1;
537   C = A - (146097 * B)/4;
538   D = ( 4 * (C + 365) ) / 1461 - 1;
539   E = C - ((1461*D) / 4);
540   M = (5 * (E - 1) + 2)/153;
541   
542   m = M + 3 - (12*(M/10));
543   day = E - (153*M + 2)/5;
544   y = 100 * B + D - 4800 + (M/10);
545   
546 #ifdef G_ENABLE_DEBUG
547   if (!g_date_valid_dmy (day, m, y)) 
548     g_warning ("\nOOPS julian: %u  computed dmy: %u %u %u\n", 
549                d->julian_days, day, m, y);
550 #endif
551   
552   d->month = m;
553   d->day   = day;
554   d->year  = y;
555   
556   d->dmy = TRUE;
557 }
558
559 /**
560  * g_date_get_weekday:
561  * @date: a #GDate
562  *
563  * Returns the day of the week for a #GDate. The date must be valid.
564  *
565  * Returns: day of the week as a #GDateWeekday.
566  */
567 GDateWeekday 
568 g_date_get_weekday (const GDate *d)
569 {
570   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_WEEKDAY);
571   
572   if (!d->julian) 
573     g_date_update_julian (d);
574
575   g_return_val_if_fail (d->julian, G_DATE_BAD_WEEKDAY);
576   
577   return ((d->julian_days - 1) % 7) + 1;
578 }
579
580 /**
581  * g_date_get_month:
582  * @date: a #GDate to get the month from
583  *
584  * Returns the month of the year. The date must be valid.
585  *
586  * Returns: month of the year as a #GDateMonth
587  */
588 GDateMonth   
589 g_date_get_month (const GDate *d)
590 {
591   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_MONTH);
592   
593   if (!d->dmy) 
594     g_date_update_dmy (d);
595
596   g_return_val_if_fail (d->dmy, G_DATE_BAD_MONTH);
597   
598   return d->month;
599 }
600
601 /**
602  * g_date_get_year:
603  * @date: a #GDate
604  *
605  * Returns the year of a #GDate. The date must be valid.
606  *
607  * Returns: year in which the date falls
608  */
609 GDateYear    
610 g_date_get_year (const GDate *d)
611 {
612   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_YEAR);
613   
614   if (!d->dmy) 
615     g_date_update_dmy (d);
616
617   g_return_val_if_fail (d->dmy, G_DATE_BAD_YEAR);  
618   
619   return d->year;
620 }
621
622 /**
623  * g_date_get_day:
624  * @date: a #GDate to extract the day of the month from
625  *
626  * Returns the day of the month. The date must be valid.
627  *
628  * Returns: day of the month
629  */
630 GDateDay     
631 g_date_get_day (const GDate *d)
632 {
633   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_DAY);
634   
635   if (!d->dmy) 
636     g_date_update_dmy (d);
637
638   g_return_val_if_fail (d->dmy, G_DATE_BAD_DAY);  
639   
640   return d->day;
641 }
642
643 /**
644  * g_date_get_julian:
645  * @date: a #GDate to extract the Julian day from
646  *
647  * Returns the Julian day or "serial number" of the #GDate. The
648  * Julian day is simply the number of days since January 1, Year 1; i.e.,
649  * January 1, Year 1 is Julian day 1; January 2, Year 1 is Julian day 2,
650  * etc. The date must be valid.
651  *
652  * Returns: Julian day
653  */
654 guint32      
655 g_date_get_julian (const GDate *d)
656 {
657   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_JULIAN);
658   
659   if (!d->julian) 
660     g_date_update_julian (d);
661
662   g_return_val_if_fail (d->julian, G_DATE_BAD_JULIAN);  
663   
664   return d->julian_days;
665 }
666
667 /**
668  * g_date_get_day_of_year:
669  * @date: a #GDate to extract day of year from
670  *
671  * Returns the day of the year, where Jan 1 is the first day of the
672  * year. The date must be valid.
673  *
674  * Returns: day of the year
675  */
676 guint        
677 g_date_get_day_of_year (const GDate *d)
678 {
679   gint idx;
680   
681   g_return_val_if_fail (g_date_valid (d), 0);
682   
683   if (!d->dmy) 
684     g_date_update_dmy (d);
685
686   g_return_val_if_fail (d->dmy, 0);  
687   
688   idx = g_date_is_leap_year (d->year) ? 1 : 0;
689   
690   return (days_in_year[idx][d->month] + d->day);
691 }
692
693 /**
694  * g_date_get_monday_week_of_year:
695  * @date: a #GDate
696  *
697  * Returns the week of the year, where weeks are understood to start on
698  * Monday. If the date is before the first Monday of the year, return
699  * 0. The date must be valid.
700  *
701  * Returns: week of the year
702  */
703 guint        
704 g_date_get_monday_week_of_year (const GDate *d)
705 {
706   GDateWeekday wd;
707   guint day;
708   GDate first;
709   
710   g_return_val_if_fail (g_date_valid (d), 0);
711   
712   if (!d->dmy) 
713     g_date_update_dmy (d);
714
715   g_return_val_if_fail (d->dmy, 0);  
716   
717   g_date_clear (&first, 1);
718   
719   g_date_set_dmy (&first, 1, 1, d->year);
720   
721   wd = g_date_get_weekday (&first) - 1; /* make Monday day 0 */
722   day = g_date_get_day_of_year (d) - 1;
723   
724   return ((day + wd)/7U + (wd == 0 ? 1 : 0));
725 }
726
727 /**
728  * g_date_get_sunday_week_of_year:
729  * @date: a #GDate
730  *
731  * Returns the week of the year during which this date falls, if weeks
732  * are understood to being on Sunday. The date must be valid. Can return
733  * 0 if the day is before the first Sunday of the year.
734  *
735  * Returns: week number
736  */
737 guint        
738 g_date_get_sunday_week_of_year (const GDate *d)
739 {
740   GDateWeekday wd;
741   guint day;
742   GDate first;
743   
744   g_return_val_if_fail (g_date_valid (d), 0);
745   
746   if (!d->dmy) 
747     g_date_update_dmy (d);
748
749   g_return_val_if_fail (d->dmy, 0);  
750   
751   g_date_clear (&first, 1);
752   
753   g_date_set_dmy (&first, 1, 1, d->year);
754   
755   wd = g_date_get_weekday (&first);
756   if (wd == 7) wd = 0; /* make Sunday day 0 */
757   day = g_date_get_day_of_year (d) - 1;
758   
759   return ((day + wd)/7U + (wd == 0 ? 1 : 0));
760 }
761
762 /**
763  * g_date_get_iso8601_week_of_year:
764  * @date: a valid #GDate
765  *
766  * Returns the week of the year, where weeks are interpreted according
767  * to ISO 8601. 
768  * 
769  * Returns: ISO 8601 week number of the year.
770  *
771  * Since: 2.6
772  **/
773 guint
774 g_date_get_iso8601_week_of_year (const GDate *d)
775 {
776   guint j, d4, L, d1, w;
777
778   g_return_val_if_fail (g_date_valid (d), 0);
779   
780   if (!d->julian)
781     g_date_update_julian (d);
782
783   g_return_val_if_fail (d->julian, 0);
784
785   /* Formula taken from the Calendar FAQ; the formula was for the
786    * Julian Period which starts on 1 January 4713 BC, so we add
787    * 1,721,425 to the number of days before doing the formula. 
788    */
789   j  = d->julian_days + 1721425;
790   d4 = (j + 31741 - (j % 7)) % 146097 % 36524 % 1461;
791   L  = d4 / 1460;
792   d1 = ((d4 - L) % 365) + L;
793   w  = d1 / 7 + 1;
794
795   return w;
796 }
797
798 /**
799  * g_date_days_between:
800  * @date1: the first date
801  * @date2: the second date
802  *
803  * Computes the number of days between two dates.
804  * If @date2 is prior to @date1, the returned value is negative.
805  * Both dates must be valid.
806  *
807  * Returns: the number of days between @date1 and @date2
808  */
809 gint
810 g_date_days_between (const GDate *d1,
811                      const GDate *d2)
812 {
813   g_return_val_if_fail (g_date_valid (d1), 0);
814   g_return_val_if_fail (g_date_valid (d2), 0);
815
816   return (gint)g_date_get_julian (d2) - (gint)g_date_get_julian (d1);
817 }
818
819 /**
820  * g_date_clear:
821  * @date: pointer to one or more dates to clear
822  * @n_dates: number of dates to clear
823  *
824  * Initializes one or more #GDate structs to a sane but invalid
825  * state. The cleared dates will not represent an existing date, but will
826  * not contain garbage. Useful to init a date declared on the stack.
827  * Validity can be tested with g_date_valid().
828  */
829 void         
830 g_date_clear (GDate *d, guint ndates)
831 {
832   g_return_if_fail (d != NULL);
833   g_return_if_fail (ndates != 0);
834   
835   memset (d, 0x0, ndates*sizeof (GDate)); 
836 }
837
838 G_LOCK_DEFINE_STATIC (g_date_global);
839
840 /* These are for the parser, output to the user should use *
841  * g_date_strftime () - this creates more never-freed memory to annoy
842  * all those memory debugger users. :-) 
843  */
844
845 static gchar *long_month_names[13] = 
846
847   NULL,
848 };
849
850 static gchar *short_month_names[13] = 
851 {
852   NULL, 
853 };
854
855 /* This tells us if we need to update the parse info */
856 static gchar *current_locale = NULL;
857
858 /* order of these in the current locale */
859 static GDateDMY dmy_order[3] = 
860 {
861    G_DATE_DAY, G_DATE_MONTH, G_DATE_YEAR
862 };
863
864 /* Where to chop two-digit years: i.e., for the 1930 default, numbers
865  * 29 and below are counted as in the year 2000, numbers 30 and above
866  * are counted as in the year 1900.  
867  */
868
869 static const GDateYear twodigit_start_year = 1930;
870
871 /* It is impossible to enter a year between 1 AD and 99 AD with this
872  * in effect.  
873  */
874 static gboolean using_twodigit_years = FALSE;
875
876 /* Adjustment of locale era to AD, non-zero means using locale era
877  */
878 static gint locale_era_adjust = 0;
879
880 struct _GDateParseTokens {
881   gint num_ints;
882   gint n[3];
883   guint month;
884 };
885
886 typedef struct _GDateParseTokens GDateParseTokens;
887
888 #define NUM_LEN 10
889
890 /* HOLDS: g_date_global_lock */
891 static void
892 g_date_fill_parse_tokens (const gchar *str, GDateParseTokens *pt)
893 {
894   gchar num[4][NUM_LEN+1];
895   gint i;
896   const guchar *s;
897   
898   /* We count 4, but store 3; so we can give an error
899    * if there are 4.
900    */
901   num[0][0] = num[1][0] = num[2][0] = num[3][0] = '\0';
902   
903   s = (const guchar *) str;
904   pt->num_ints = 0;
905   while (*s && pt->num_ints < 4) 
906     {
907       
908       i = 0;
909       while (*s && g_ascii_isdigit (*s) && i < NUM_LEN)
910         {
911           num[pt->num_ints][i] = *s;
912           ++s; 
913           ++i;
914         }
915       
916       if (i > 0) 
917         {
918           num[pt->num_ints][i] = '\0';
919           ++(pt->num_ints);
920         }
921       
922       if (*s == '\0') break;
923       
924       ++s;
925     }
926   
927   pt->n[0] = pt->num_ints > 0 ? atoi (num[0]) : 0;
928   pt->n[1] = pt->num_ints > 1 ? atoi (num[1]) : 0;
929   pt->n[2] = pt->num_ints > 2 ? atoi (num[2]) : 0;
930   
931   pt->month = G_DATE_BAD_MONTH;
932   
933   if (pt->num_ints < 3)
934     {
935       gchar *casefold;
936       gchar *normalized;
937       
938       casefold = g_utf8_casefold (str, -1);
939       normalized = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
940       g_free (casefold);
941
942       i = 1;
943       while (i < 13)
944         {
945           if (long_month_names[i] != NULL) 
946             {
947               const gchar *found = strstr (normalized, long_month_names[i]);
948               
949               if (found != NULL)
950                 {
951                   pt->month = i;
952                   break;
953                 }
954             }
955           
956           if (short_month_names[i] != NULL) 
957             {
958               const gchar *found = strstr (normalized, short_month_names[i]);
959               
960               if (found != NULL)
961                 {
962                   pt->month = i;
963                   break;
964                 }
965             }
966
967           ++i;
968         }
969
970       g_free (normalized);
971     }
972 }
973
974 /* HOLDS: g_date_global_lock */
975 static void
976 g_date_prepare_to_parse (const gchar      *str, 
977                          GDateParseTokens *pt)
978 {
979   const gchar *locale = setlocale (LC_TIME, NULL);
980   gboolean recompute_localeinfo = FALSE;
981   GDate d;
982   
983   g_return_if_fail (locale != NULL); /* should not happen */
984   
985   g_date_clear (&d, 1);              /* clear for scratch use */
986   
987   if ( (current_locale == NULL) || (strcmp (locale, current_locale) != 0) ) 
988     recompute_localeinfo = TRUE;  /* Uh, there used to be a reason for the temporary */
989   
990   if (recompute_localeinfo)
991     {
992       int i = 1;
993       GDateParseTokens testpt;
994       gchar buf[128];
995       
996       g_free (current_locale); /* still works if current_locale == NULL */
997       
998       current_locale = g_strdup (locale);
999       
1000       short_month_names[0] = "Error";
1001       long_month_names[0] = "Error";
1002
1003       while (i < 13) 
1004         {
1005           gchar *casefold;
1006           
1007           g_date_set_dmy (&d, 1, i, 1);
1008           
1009           g_return_if_fail (g_date_valid (&d));
1010           
1011           g_date_strftime (buf, 127, "%b", &d);
1012
1013           casefold = g_utf8_casefold (buf, -1);
1014           g_free (short_month_names[i]);
1015           short_month_names[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
1016           g_free (casefold);
1017           
1018           g_date_strftime (buf, 127, "%B", &d);
1019           casefold = g_utf8_casefold (buf, -1);
1020           g_free (long_month_names[i]);
1021           long_month_names[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
1022           g_free (casefold);
1023           
1024           ++i;
1025         }
1026       
1027       /* Determine DMY order */
1028       
1029       /* had to pick a random day - don't change this, some strftimes
1030        * are broken on some days, and this one is good so far. */
1031       g_date_set_dmy (&d, 4, 7, 1976);
1032       
1033       g_date_strftime (buf, 127, "%x", &d);
1034       
1035       g_date_fill_parse_tokens (buf, &testpt);
1036       
1037       i = 0;
1038       while (i < testpt.num_ints)
1039         {
1040           switch (testpt.n[i])
1041             {
1042             case 7:
1043               dmy_order[i] = G_DATE_MONTH;
1044               break;
1045             case 4:
1046               dmy_order[i] = G_DATE_DAY;
1047               break;
1048             case 76:
1049               using_twodigit_years = TRUE; /* FALL THRU */
1050             case 1976:
1051               dmy_order[i] = G_DATE_YEAR;
1052               break;
1053             default:
1054               /* assume locale era */
1055               locale_era_adjust = 1976 - testpt.n[i];
1056               dmy_order[i] = G_DATE_YEAR;
1057               break;
1058             }
1059           ++i;
1060         }
1061       
1062 #if defined(G_ENABLE_DEBUG) && 0
1063       DEBUG_MSG (("**GDate prepared a new set of locale-specific parse rules."));
1064       i = 1;
1065       while (i < 13) 
1066         {
1067           DEBUG_MSG (("  %s   %s", long_month_names[i], short_month_names[i]));
1068           ++i;
1069         }
1070       if (using_twodigit_years)
1071         {
1072           DEBUG_MSG (("**Using twodigit years with cutoff year: %u", twodigit_start_year));
1073         }
1074       { 
1075         gchar *strings[3];
1076         i = 0;
1077         while (i < 3)
1078           {
1079             switch (dmy_order[i])
1080               {
1081               case G_DATE_MONTH:
1082                 strings[i] = "Month";
1083                 break;
1084               case G_DATE_YEAR:
1085                 strings[i] = "Year";
1086                 break;
1087               case G_DATE_DAY:
1088                 strings[i] = "Day";
1089                 break;
1090               default:
1091                 strings[i] = NULL;
1092                 break;
1093               }
1094             ++i;
1095           }
1096         DEBUG_MSG (("**Order: %s, %s, %s", strings[0], strings[1], strings[2]));
1097         DEBUG_MSG (("**Sample date in this locale: `%s'", buf));
1098       }
1099 #endif
1100     }
1101   
1102   g_date_fill_parse_tokens (str, pt);
1103 }
1104
1105 /**
1106  * g_date_set_parse:
1107  * @date: a #GDate to fill in
1108  * @str: string to parse
1109  *
1110  * Parses a user-inputted string @str, and try to figure out what date it
1111  * represents, taking the <link linkend="setlocale">current locale</link>
1112  * into account. If the string is successfully parsed, the date will be
1113  * valid after the call. Otherwise, it will be invalid. You should check
1114  * using g_date_valid() to see whether the parsing succeeded.
1115  *
1116  * This function is not appropriate for file formats and the like; it
1117  * isn't very precise, and its exact behavior varies with the locale.
1118  * It's intended to be a heuristic routine that guesses what the user
1119  * means by a given string (and it does work pretty well in that
1120  * capacity).
1121  */
1122 void         
1123 g_date_set_parse (GDate       *d, 
1124                   const gchar *str)
1125 {
1126   GDateParseTokens pt;
1127   guint m = G_DATE_BAD_MONTH, day = G_DATE_BAD_DAY, y = G_DATE_BAD_YEAR;
1128   
1129   g_return_if_fail (d != NULL);
1130   
1131   /* set invalid */
1132   g_date_clear (d, 1);
1133   
1134   G_LOCK (g_date_global);
1135
1136   g_date_prepare_to_parse (str, &pt);
1137   
1138   DEBUG_MSG (("Found %d ints, `%d' `%d' `%d' and written out month %d", 
1139               pt.num_ints, pt.n[0], pt.n[1], pt.n[2], pt.month));
1140   
1141   
1142   if (pt.num_ints == 4) 
1143     {
1144       G_UNLOCK (g_date_global);
1145       return; /* presumably a typo; bail out. */
1146     }
1147   
1148   if (pt.num_ints > 1)
1149     {
1150       int i = 0;
1151       int j = 0;
1152       
1153       g_assert (pt.num_ints < 4); /* i.e., it is 2 or 3 */
1154       
1155       while (i < pt.num_ints && j < 3) 
1156         {
1157           switch (dmy_order[j])
1158             {
1159             case G_DATE_MONTH:
1160             {
1161               if (pt.num_ints == 2 && pt.month != G_DATE_BAD_MONTH)
1162                 {
1163                   m = pt.month;
1164                   ++j;      /* skip months, but don't skip this number */
1165                   continue;
1166                 }
1167               else 
1168                 m = pt.n[i];
1169             }
1170             break;
1171             case G_DATE_DAY:
1172             {
1173               if (pt.num_ints == 2 && pt.month == G_DATE_BAD_MONTH)
1174                 {
1175                   day = 1;
1176                   ++j;      /* skip days, since we may have month/year */
1177                   continue;
1178                 }
1179               day = pt.n[i];
1180             }
1181             break;
1182             case G_DATE_YEAR:
1183             {
1184               y  = pt.n[i];
1185               
1186               if (locale_era_adjust != 0)
1187                 {
1188                   y += locale_era_adjust;
1189                 }
1190               else if (using_twodigit_years && y < 100)
1191                 {
1192                   guint two     =  twodigit_start_year % 100;
1193                   guint century = (twodigit_start_year / 100) * 100;
1194                   
1195                   if (y < two)
1196                     century += 100;
1197                   
1198                   y += century;
1199                 }
1200             }
1201             break;
1202             default:
1203               break;
1204             }
1205           
1206           ++i;
1207           ++j;
1208         }
1209       
1210       
1211       if (pt.num_ints == 3 && !g_date_valid_dmy (day, m, y))
1212         {
1213           /* Try YYYY MM DD */
1214           y   = pt.n[0];
1215           m   = pt.n[1];
1216           day = pt.n[2];
1217           
1218           if (using_twodigit_years && y < 100) 
1219             y = G_DATE_BAD_YEAR; /* avoids ambiguity */
1220         }
1221       else if (pt.num_ints == 2)
1222         {
1223           if (m == G_DATE_BAD_MONTH && pt.month != G_DATE_BAD_MONTH)
1224             m = pt.month;
1225         }
1226     }
1227   else if (pt.num_ints == 1) 
1228     {
1229       if (pt.month != G_DATE_BAD_MONTH)
1230         {
1231           /* Month name and year? */
1232           m    = pt.month;
1233           day  = 1;
1234           y = pt.n[0];
1235         }
1236       else
1237         {
1238           /* Try yyyymmdd and yymmdd */
1239           
1240           m   = (pt.n[0]/100) % 100;
1241           day = pt.n[0] % 100;
1242           y   = pt.n[0]/10000;
1243           
1244           /* FIXME move this into a separate function */
1245           if (using_twodigit_years && y < 100)
1246             {
1247               guint two     =  twodigit_start_year % 100;
1248               guint century = (twodigit_start_year / 100) * 100;
1249               
1250               if (y < two)
1251                 century += 100;
1252               
1253               y += century;
1254             }
1255         }
1256     }
1257   
1258   /* See if we got anything valid out of all this. */
1259   /* y < 8000 is to catch 19998 style typos; the library is OK up to 65535 or so */
1260   if (y < 8000 && g_date_valid_dmy (day, m, y)) 
1261     {
1262       d->month = m;
1263       d->day   = day;
1264       d->year  = y;
1265       d->dmy   = TRUE;
1266     }
1267 #ifdef G_ENABLE_DEBUG
1268   else 
1269     {
1270       DEBUG_MSG (("Rejected DMY %u %u %u", day, m, y));
1271     }
1272 #endif
1273   G_UNLOCK (g_date_global);
1274 }
1275
1276 /**
1277  * g_date_set_time_t:
1278  * @date: a #GDate 
1279  * @timet: <type>time_t</type> value to set
1280  *
1281  * Sets the value of a date to the date corresponding to a time 
1282  * specified as a time_t. The time to date conversion is done using 
1283  * the user's current timezone.
1284  *
1285  * To set the value of a date to the current day, you could write:
1286  * |[
1287  *  g_date_set_time_t (date, time (NULL)); 
1288  * ]|
1289  *
1290  * Since: 2.10
1291  */
1292 void         
1293 g_date_set_time_t (GDate *date,
1294                    time_t timet)
1295 {
1296   struct tm tm;
1297   
1298   g_return_if_fail (date != NULL);
1299   
1300 #ifdef HAVE_LOCALTIME_R
1301   localtime_r (&timet, &tm);
1302 #else
1303   {
1304     struct tm *ptm = localtime (&timet);
1305
1306     if (ptm == NULL)
1307       {
1308         /* Happens at least in Microsoft's C library if you pass a
1309          * negative time_t. Use 2000-01-01 as default date.
1310          */
1311 #ifndef G_DISABLE_CHECKS
1312         g_return_if_fail_warning (G_LOG_DOMAIN, "g_date_set_time", "ptm != NULL");
1313 #endif
1314
1315         tm.tm_mon = 0;
1316         tm.tm_mday = 1;
1317         tm.tm_year = 100;
1318       }
1319     else
1320       memcpy ((void *) &tm, (void *) ptm, sizeof(struct tm));
1321   }
1322 #endif
1323   
1324   date->julian = FALSE;
1325   
1326   date->month = tm.tm_mon + 1;
1327   date->day   = tm.tm_mday;
1328   date->year  = tm.tm_year + 1900;
1329   
1330   g_return_if_fail (g_date_valid_dmy (date->day, date->month, date->year));
1331   
1332   date->dmy    = TRUE;
1333 }
1334
1335
1336 /**
1337  * g_date_set_time:
1338  * @date: a #GDate.
1339  * @time_: #GTime value to set.
1340  *
1341  * Sets the value of a date from a #GTime value.
1342  * The time to date conversion is done using the user's current timezone.
1343  *
1344  * Deprecated: 2.10: Use g_date_set_time_t() instead.
1345  */
1346 void
1347 g_date_set_time (GDate *date,
1348                  GTime  time_)
1349 {
1350   g_date_set_time_t (date, (time_t) time_);
1351 }
1352
1353 /**
1354  * g_date_set_time_val:
1355  * @date: a #GDate 
1356  * @timeval: #GTimeVal value to set
1357  *
1358  * Sets the value of a date from a #GTimeVal value.  Note that the
1359  * @tv_usec member is ignored, because #GDate can't make use of the
1360  * additional precision.
1361  *
1362  * The time to date conversion is done using the user's current timezone.
1363  *
1364  * Since: 2.10
1365  */
1366 void
1367 g_date_set_time_val (GDate    *date,
1368                      GTimeVal *timeval)
1369 {
1370   g_date_set_time_t (date, (time_t) timeval->tv_sec);
1371 }
1372
1373 /**
1374  * g_date_set_month:
1375  * @date: a #GDate
1376  * @month: month to set
1377  *
1378  * Sets the month of the year for a #GDate.  If the resulting
1379  * day-month-year triplet is invalid, the date will be invalid.
1380  */
1381 void         
1382 g_date_set_month (GDate     *d, 
1383                   GDateMonth m)
1384 {
1385   g_return_if_fail (d != NULL);
1386   g_return_if_fail (g_date_valid_month (m));
1387
1388   if (d->julian && !d->dmy) g_date_update_dmy(d);
1389   d->julian = FALSE;
1390   
1391   d->month = m;
1392   
1393   if (g_date_valid_dmy (d->day, d->month, d->year))
1394     d->dmy = TRUE;
1395   else 
1396     d->dmy = FALSE;
1397 }
1398
1399 /**
1400  * g_date_set_day:
1401  * @date: a #GDate
1402  * @day: day to set
1403  *
1404  * Sets the day of the month for a #GDate. If the resulting
1405  * day-month-year triplet is invalid, the date will be invalid.
1406  */
1407 void         
1408 g_date_set_day (GDate    *d, 
1409                 GDateDay  day)
1410 {
1411   g_return_if_fail (d != NULL);
1412   g_return_if_fail (g_date_valid_day (day));
1413   
1414   if (d->julian && !d->dmy) g_date_update_dmy(d);
1415   d->julian = FALSE;
1416   
1417   d->day = day;
1418   
1419   if (g_date_valid_dmy (d->day, d->month, d->year))
1420     d->dmy = TRUE;
1421   else 
1422     d->dmy = FALSE;
1423 }
1424
1425 /**
1426  * g_date_set_year:
1427  * @date: a #GDate
1428  * @year: year to set
1429  *
1430  * Sets the year for a #GDate. If the resulting day-month-year
1431  * triplet is invalid, the date will be invalid.
1432  */
1433 void         
1434 g_date_set_year (GDate     *d, 
1435                  GDateYear  y)
1436 {
1437   g_return_if_fail (d != NULL);
1438   g_return_if_fail (g_date_valid_year (y));
1439   
1440   if (d->julian && !d->dmy) g_date_update_dmy(d);
1441   d->julian = FALSE;
1442   
1443   d->year = y;
1444   
1445   if (g_date_valid_dmy (d->day, d->month, d->year))
1446     d->dmy = TRUE;
1447   else 
1448     d->dmy = FALSE;
1449 }
1450
1451 /**
1452  * g_date_set_dmy:
1453  * @date: a #GDate
1454  * @day: day
1455  * @month: month
1456  * @y: year
1457  *
1458  * Sets the value of a #GDate from a day, month, and year.
1459  * The day-month-year triplet must be valid; if you aren't
1460  * sure it is, call g_date_valid_dmy() to check before you
1461  * set it.
1462  */
1463 void         
1464 g_date_set_dmy (GDate      *d, 
1465                 GDateDay    day, 
1466                 GDateMonth  m, 
1467                 GDateYear   y)
1468 {
1469   g_return_if_fail (d != NULL);
1470   g_return_if_fail (g_date_valid_dmy (day, m, y));
1471   
1472   d->julian = FALSE;
1473   
1474   d->month = m;
1475   d->day   = day;
1476   d->year  = y;
1477   
1478   d->dmy = TRUE;
1479 }
1480
1481 /**
1482  * g_date_set_julian:
1483  * @date: a #GDate
1484  * @julian_date: Julian day number (days since January 1, Year 1)
1485  *
1486  * Sets the value of a #GDate from a Julian day number.
1487  */
1488 void         
1489 g_date_set_julian (GDate   *d, 
1490                    guint32  j)
1491 {
1492   g_return_if_fail (d != NULL);
1493   g_return_if_fail (g_date_valid_julian (j));
1494   
1495   d->julian_days = j;
1496   d->julian = TRUE;
1497   d->dmy = FALSE;
1498 }
1499
1500 /**
1501  * g_date_is_first_of_month:
1502  * @date: a #GDate to check
1503  *
1504  * Returns %TRUE if the date is on the first of a month.
1505  * The date must be valid.
1506  *
1507  * Returns: %TRUE if the date is the first of the month
1508  */
1509 gboolean     
1510 g_date_is_first_of_month (const GDate *d)
1511 {
1512   g_return_val_if_fail (g_date_valid (d), FALSE);
1513   
1514   if (!d->dmy) 
1515     g_date_update_dmy (d);
1516
1517   g_return_val_if_fail (d->dmy, FALSE);  
1518   
1519   if (d->day == 1) return TRUE;
1520   else return FALSE;
1521 }
1522
1523 /**
1524  * g_date_is_last_of_month:
1525  * @date: a #GDate to check
1526  *
1527  * Returns %TRUE if the date is the last day of the month.
1528  * The date must be valid.
1529  *
1530  * Returns: %TRUE if the date is the last day of the month
1531  */
1532 gboolean     
1533 g_date_is_last_of_month (const GDate *d)
1534 {
1535   gint idx;
1536   
1537   g_return_val_if_fail (g_date_valid (d), FALSE);
1538   
1539   if (!d->dmy) 
1540     g_date_update_dmy (d);
1541
1542   g_return_val_if_fail (d->dmy, FALSE);  
1543   
1544   idx = g_date_is_leap_year (d->year) ? 1 : 0;
1545   
1546   if (d->day == days_in_months[idx][d->month]) return TRUE;
1547   else return FALSE;
1548 }
1549
1550 /**
1551  * g_date_add_days:
1552  * @date: a #GDate to increment
1553  * @n_days: number of days to move the date forward
1554  *
1555  * Increments a date some number of days.
1556  * To move forward by weeks, add weeks*7 days.
1557  * The date must be valid.
1558  */
1559 void         
1560 g_date_add_days (GDate *d, 
1561                  guint  ndays)
1562 {
1563   g_return_if_fail (g_date_valid (d));
1564   
1565   if (!d->julian)
1566     g_date_update_julian (d);
1567
1568   g_return_if_fail (d->julian);
1569   
1570   d->julian_days += ndays;
1571   d->dmy = FALSE;
1572 }
1573
1574 /**
1575  * g_date_subtract_days:
1576  * @date: a #GDate to decrement
1577  * @n_days: number of days to move
1578  *
1579  * Moves a date some number of days into the past.
1580  * To move by weeks, just move by weeks*7 days.
1581  * The date must be valid.
1582  */
1583 void         
1584 g_date_subtract_days (GDate *d, 
1585                       guint  ndays)
1586 {
1587   g_return_if_fail (g_date_valid (d));
1588   
1589   if (!d->julian)
1590     g_date_update_julian (d);
1591
1592   g_return_if_fail (d->julian);
1593   g_return_if_fail (d->julian_days > ndays);
1594   
1595   d->julian_days -= ndays;
1596   d->dmy = FALSE;
1597 }
1598
1599 /**
1600  * g_date_add_months:
1601  * @date: a #GDate to increment
1602  * @n_months: number of months to move forward
1603  *
1604  * Increments a date by some number of months.
1605  * If the day of the month is greater than 28,
1606  * this routine may change the day of the month
1607  * (because the destination month may not have
1608  * the current day in it). The date must be valid.
1609  */
1610 void         
1611 g_date_add_months (GDate *d, 
1612                    guint  nmonths)
1613 {
1614   guint years, months;
1615   gint idx;
1616   
1617   g_return_if_fail (g_date_valid (d));
1618   
1619   if (!d->dmy) 
1620     g_date_update_dmy (d);
1621
1622   g_return_if_fail (d->dmy);  
1623   
1624   nmonths += d->month - 1;
1625   
1626   years  = nmonths/12;
1627   months = nmonths%12;
1628   
1629   d->month = months + 1;
1630   d->year  += years;
1631   
1632   idx = g_date_is_leap_year (d->year) ? 1 : 0;
1633   
1634   if (d->day > days_in_months[idx][d->month])
1635     d->day = days_in_months[idx][d->month];
1636   
1637   d->julian = FALSE;
1638   
1639   g_return_if_fail (g_date_valid (d));
1640 }
1641
1642 /**
1643  * g_date_subtract_months:
1644  * @date: a #GDate to decrement
1645  * @n_months: number of months to move
1646  *
1647  * Moves a date some number of months into the past.
1648  * If the current day of the month doesn't exist in
1649  * the destination month, the day of the month
1650  * may change. The date must be valid.
1651  */
1652 void         
1653 g_date_subtract_months (GDate *d, 
1654                         guint  nmonths)
1655 {
1656   guint years, months;
1657   gint idx;
1658   
1659   g_return_if_fail (g_date_valid (d));
1660   
1661   if (!d->dmy) 
1662     g_date_update_dmy (d);
1663
1664   g_return_if_fail (d->dmy);  
1665   
1666   years  = nmonths/12;
1667   months = nmonths%12;
1668   
1669   g_return_if_fail (d->year > years);
1670   
1671   d->year  -= years;
1672   
1673   if (d->month > months) d->month -= months;
1674   else 
1675     {
1676       months -= d->month;
1677       d->month = 12 - months;
1678       d->year -= 1;
1679     }
1680   
1681   idx = g_date_is_leap_year (d->year) ? 1 : 0;
1682   
1683   if (d->day > days_in_months[idx][d->month])
1684     d->day = days_in_months[idx][d->month];
1685   
1686   d->julian = FALSE;
1687   
1688   g_return_if_fail (g_date_valid (d));
1689 }
1690
1691 /**
1692  * g_date_add_years:
1693  * @date: a #GDate to increment
1694  * @n_years: number of years to move forward
1695  *
1696  * Increments a date by some number of years.
1697  * If the date is February 29, and the destination
1698  * year is not a leap year, the date will be changed
1699  * to February 28. The date must be valid.
1700  */
1701 void         
1702 g_date_add_years (GDate *d, 
1703                   guint  nyears)
1704 {
1705   g_return_if_fail (g_date_valid (d));
1706   
1707   if (!d->dmy) 
1708     g_date_update_dmy (d);
1709
1710   g_return_if_fail (d->dmy);  
1711   
1712   d->year += nyears;
1713   
1714   if (d->month == 2 && d->day == 29)
1715     {
1716       if (!g_date_is_leap_year (d->year))
1717         d->day = 28;
1718     }
1719   
1720   d->julian = FALSE;
1721 }
1722
1723 /**
1724  * g_date_subtract_years:
1725  * @date: a #GDate to decrement
1726  * @n_years: number of years to move
1727  *
1728  * Moves a date some number of years into the past.
1729  * If the current day doesn't exist in the destination
1730  * year (i.e. it's February 29 and you move to a non-leap-year)
1731  * then the day is changed to February 29. The date
1732  * must be valid.
1733  */
1734 void         
1735 g_date_subtract_years (GDate *d, 
1736                        guint  nyears)
1737 {
1738   g_return_if_fail (g_date_valid (d));
1739   
1740   if (!d->dmy) 
1741     g_date_update_dmy (d);
1742
1743   g_return_if_fail (d->dmy);  
1744   g_return_if_fail (d->year > nyears);
1745   
1746   d->year -= nyears;
1747   
1748   if (d->month == 2 && d->day == 29)
1749     {
1750       if (!g_date_is_leap_year (d->year))
1751         d->day = 28;
1752     }
1753   
1754   d->julian = FALSE;
1755 }
1756
1757 /**
1758  * g_date_is_leap_year:
1759  * @year: year to check
1760  *
1761  * Returns %TRUE if the year is a leap year.
1762  * <footnote><para>For the purposes of this function,
1763  * leap year is every year divisible by 4 unless that year
1764  * is divisible by 100. If it is divisible by 100 it would
1765  * be a leap year only if that year is also divisible
1766  * by 400.</para></footnote>
1767  *
1768  * Returns: %TRUE if the year is a leap year
1769  */
1770 gboolean     
1771 g_date_is_leap_year (GDateYear year)
1772 {
1773   g_return_val_if_fail (g_date_valid_year (year), FALSE);
1774   
1775   return ( (((year % 4) == 0) && ((year % 100) != 0)) ||
1776            (year % 400) == 0 );
1777 }
1778
1779 /**
1780  * g_date_get_days_in_month:
1781  * @month: month
1782  * @year: year
1783  *
1784  * Returns the number of days in a month, taking leap
1785  * years into account.
1786  *
1787  * Returns: number of days in @month during the @year
1788  */
1789 guint8         
1790 g_date_get_days_in_month (GDateMonth month, 
1791                           GDateYear  year)
1792 {
1793   gint idx;
1794   
1795   g_return_val_if_fail (g_date_valid_year (year), 0);
1796   g_return_val_if_fail (g_date_valid_month (month), 0);
1797   
1798   idx = g_date_is_leap_year (year) ? 1 : 0;
1799   
1800   return days_in_months[idx][month];
1801 }
1802
1803 /**
1804  * g_date_get_monday_weeks_in_year:
1805  * @year: a year
1806  *
1807  * Returns the number of weeks in the year, where weeks
1808  * are taken to start on Monday. Will be 52 or 53. The
1809  * date must be valid. (Years always have 52 7-day periods,
1810  * plus 1 or 2 extra days depending on whether it's a leap
1811  * year. This function is basically telling you how many
1812  * Mondays are in the year, i.e. there are 53 Mondays if
1813  * one of the extra days happens to be a Monday.)
1814  *
1815  * Returns: number of Mondays in the year
1816  */
1817 guint8       
1818 g_date_get_monday_weeks_in_year (GDateYear year)
1819 {
1820   GDate d;
1821   
1822   g_return_val_if_fail (g_date_valid_year (year), 0);
1823   
1824   g_date_clear (&d, 1);
1825   g_date_set_dmy (&d, 1, 1, year);
1826   if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1827   g_date_set_dmy (&d, 31, 12, year);
1828   if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1829   if (g_date_is_leap_year (year)) 
1830     {
1831       g_date_set_dmy (&d, 2, 1, year);
1832       if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1833       g_date_set_dmy (&d, 30, 12, year);
1834       if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1835     }
1836   return 52;
1837 }
1838
1839 /**
1840  * g_date_get_sunday_weeks_in_year:
1841  * @year: year to count weeks in
1842  *
1843  * Returns the number of weeks in the year, where weeks
1844  * are taken to start on Sunday. Will be 52 or 53. The
1845  * date must be valid. (Years always have 52 7-day periods,
1846  * plus 1 or 2 extra days depending on whether it's a leap
1847  * year. This function is basically telling you how many
1848  * Sundays are in the year, i.e. there are 53 Sundays if
1849  * one of the extra days happens to be a Sunday.)
1850  */
1851 guint8       
1852 g_date_get_sunday_weeks_in_year (GDateYear year)
1853 {
1854   GDate d;
1855   
1856   g_return_val_if_fail (g_date_valid_year (year), 0);
1857   
1858   g_date_clear (&d, 1);
1859   g_date_set_dmy (&d, 1, 1, year);
1860   if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1861   g_date_set_dmy (&d, 31, 12, year);
1862   if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1863   if (g_date_is_leap_year (year)) 
1864     {
1865       g_date_set_dmy (&d, 2, 1, year);
1866       if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1867       g_date_set_dmy (&d, 30, 12, year);
1868       if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1869     }
1870   return 52;
1871 }
1872
1873 /**
1874  * g_date_compare:
1875  * @lhs: first date to compare
1876  * @rhs: second date to compare
1877  *
1878  * qsort()-style comparsion function for dates.
1879  * Both dates must be valid.
1880  *
1881  * Returns: 0 for equal, less than zero if @lhs is less than @rhs,
1882  *     greater than zero if @lhs is greater than @rhs
1883  */
1884 gint         
1885 g_date_compare (const GDate *lhs, 
1886                 const GDate *rhs)
1887 {
1888   g_return_val_if_fail (lhs != NULL, 0);
1889   g_return_val_if_fail (rhs != NULL, 0);
1890   g_return_val_if_fail (g_date_valid (lhs), 0);
1891   g_return_val_if_fail (g_date_valid (rhs), 0);
1892   
1893   /* Remember the self-comparison case! I think it works right now. */
1894   
1895   while (TRUE)
1896     {
1897       if (lhs->julian && rhs->julian) 
1898         {
1899           if (lhs->julian_days < rhs->julian_days) return -1;
1900           else if (lhs->julian_days > rhs->julian_days) return 1;
1901           else                                          return 0;
1902         }
1903       else if (lhs->dmy && rhs->dmy) 
1904         {
1905           if (lhs->year < rhs->year)               return -1;
1906           else if (lhs->year > rhs->year)               return 1;
1907           else 
1908             {
1909               if (lhs->month < rhs->month)         return -1;
1910               else if (lhs->month > rhs->month)         return 1;
1911               else 
1912                 {
1913                   if (lhs->day < rhs->day)              return -1;
1914                   else if (lhs->day > rhs->day)              return 1;
1915                   else                                       return 0;
1916                 }
1917               
1918             }
1919           
1920         }
1921       else
1922         {
1923           if (!lhs->julian) g_date_update_julian (lhs);
1924           if (!rhs->julian) g_date_update_julian (rhs);
1925           g_return_val_if_fail (lhs->julian, 0);
1926           g_return_val_if_fail (rhs->julian, 0);
1927         }
1928       
1929     }
1930   return 0; /* warnings */
1931 }
1932
1933 /**
1934  * g_date_to_struct_tm:
1935  * @date: a #GDate to set the <structname>struct tm</structname> from
1936  * @tm: <structname>struct tm</structname> to fill
1937  *
1938  * Fills in the date-related bits of a <structname>struct tm</structname>
1939  * using the @date value. Initializes the non-date parts with something
1940  * sane but meaningless.
1941  */
1942 void        
1943 g_date_to_struct_tm (const GDate *d, 
1944                      struct tm   *tm)
1945 {
1946   GDateWeekday day;
1947      
1948   g_return_if_fail (g_date_valid (d));
1949   g_return_if_fail (tm != NULL);
1950   
1951   if (!d->dmy) 
1952     g_date_update_dmy (d);
1953
1954   g_return_if_fail (d->dmy);
1955   
1956   /* zero all the irrelevant fields to be sure they're valid */
1957   
1958   /* On Linux and maybe other systems, there are weird non-POSIX
1959    * fields on the end of struct tm that choke strftime if they
1960    * contain garbage.  So we need to 0 the entire struct, not just the
1961    * fields we know to exist. 
1962    */
1963   
1964   memset (tm, 0x0, sizeof (struct tm));
1965   
1966   tm->tm_mday = d->day;
1967   tm->tm_mon  = d->month - 1; /* 0-11 goes in tm */
1968   tm->tm_year = ((int)d->year) - 1900; /* X/Open says tm_year can be negative */
1969   
1970   day = g_date_get_weekday (d);
1971   if (day == 7) day = 0; /* struct tm wants days since Sunday, so Sunday is 0 */
1972   
1973   tm->tm_wday = (int)day;
1974   
1975   tm->tm_yday = g_date_get_day_of_year (d) - 1; /* 0 to 365 */
1976   tm->tm_isdst = -1; /* -1 means "information not available" */
1977 }
1978
1979 /**
1980  * g_date_clamp:
1981  * @date: a #GDate to clamp
1982  * @min_date: minimum accepted value for @date
1983  * @max_date: maximum accepted value for @date
1984  *
1985  * If @date is prior to @min_date, sets @date equal to @min_date.
1986  * If @date falls after @max_date, sets @date equal to @max_date.
1987  * Otherwise, @date is unchanged.
1988  * Either of @min_date and @max_date may be %NULL.
1989  * All non-%NULL dates must be valid.
1990  */
1991 void
1992 g_date_clamp (GDate       *date,
1993               const GDate *min_date,
1994               const GDate *max_date)
1995 {
1996   g_return_if_fail (g_date_valid (date));
1997
1998   if (min_date != NULL)
1999     g_return_if_fail (g_date_valid (min_date));
2000
2001   if (max_date != NULL)
2002     g_return_if_fail (g_date_valid (max_date));
2003
2004   if (min_date != NULL && max_date != NULL)
2005     g_return_if_fail (g_date_compare (min_date, max_date) <= 0);
2006
2007   if (min_date && g_date_compare (date, min_date) < 0)
2008     *date = *min_date;
2009
2010   if (max_date && g_date_compare (max_date, date) < 0)
2011     *date = *max_date;
2012 }
2013
2014 /**
2015  * g_date_order:
2016  * @date1: the first date
2017  * @date2: the second date
2018  *
2019  * Checks if @date1 is less than or equal to @date2,
2020  * and swap the values if this is not the case.
2021  */
2022 void
2023 g_date_order (GDate *date1,
2024               GDate *date2)
2025 {
2026   g_return_if_fail (g_date_valid (date1));
2027   g_return_if_fail (g_date_valid (date2));
2028
2029   if (g_date_compare (date1, date2) > 0)
2030     {
2031       GDate tmp = *date1;
2032       *date1 = *date2;
2033       *date2 = tmp;
2034     }
2035 }
2036
2037 #ifdef G_OS_WIN32
2038 static gsize
2039 win32_strftime_helper (const GDate     *d,
2040                        const gchar     *format,
2041                        const struct tm *tm,
2042                        gchar           *s,
2043                        gsize            slen)
2044 {
2045   SYSTEMTIME systemtime;
2046   TIME_ZONE_INFORMATION tzinfo;
2047   LCID lcid;
2048   int n, k;
2049   GArray *result;
2050   const gchar *p;
2051   gunichar c;
2052   const wchar_t digits[] = L"0123456789";
2053   gchar *convbuf;
2054   glong convlen = 0;
2055   gsize retval;
2056
2057   systemtime.wYear = tm->tm_year + 1900;
2058   systemtime.wMonth = tm->tm_mon + 1;
2059   systemtime.wDayOfWeek = tm->tm_wday;
2060   systemtime.wDay = tm->tm_mday;
2061   systemtime.wHour = tm->tm_hour;
2062   systemtime.wMinute = tm->tm_min;
2063   systemtime.wSecond = tm->tm_sec;
2064   systemtime.wMilliseconds = 0;
2065   
2066   lcid = GetThreadLocale ();
2067   result = g_array_sized_new (FALSE, FALSE, sizeof (wchar_t), MAX (128, strlen (format) * 2));
2068
2069   p = format;
2070   while (*p)
2071     {
2072       c = g_utf8_get_char (p);
2073       if (c == '%')
2074         {
2075           p = g_utf8_next_char (p);
2076           if (!*p)
2077             {
2078               s[0] = '\0';
2079               g_array_free (result, TRUE);
2080
2081               return 0;
2082             }
2083           
2084           c = g_utf8_get_char (p);
2085           if (c == 'E' || c == 'O')
2086             {
2087               /* Ignore modified conversion specifiers for now. */
2088               p = g_utf8_next_char (p);
2089               if (!*p)
2090                 {
2091                   s[0] = '\0';
2092                   g_array_free (result, TRUE);
2093                   
2094                   return 0;
2095                 }
2096
2097               c = g_utf8_get_char (p);
2098             }
2099
2100           switch (c)
2101             {
2102             case 'a':
2103               if (systemtime.wDayOfWeek == 0)
2104                 k = 6;
2105               else
2106                 k = systemtime.wDayOfWeek - 1;
2107               n = GetLocaleInfoW (lcid, LOCALE_SABBREVDAYNAME1+k, NULL, 0);
2108               g_array_set_size (result, result->len + n);
2109               GetLocaleInfoW (lcid, LOCALE_SABBREVDAYNAME1+k, ((wchar_t *) result->data) + result->len - n, n);
2110               g_array_set_size (result, result->len - 1);
2111               break;
2112             case 'A':
2113               if (systemtime.wDayOfWeek == 0)
2114                 k = 6;
2115               else
2116                 k = systemtime.wDayOfWeek - 1;
2117               n = GetLocaleInfoW (lcid, LOCALE_SDAYNAME1+k, NULL, 0);
2118               g_array_set_size (result, result->len + n);
2119               GetLocaleInfoW (lcid, LOCALE_SDAYNAME1+k, ((wchar_t *) result->data) + result->len - n, n);
2120               g_array_set_size (result, result->len - 1);
2121               break;
2122             case 'b':
2123             case 'h':
2124               n = GetLocaleInfoW (lcid, LOCALE_SABBREVMONTHNAME1+systemtime.wMonth-1, NULL, 0);
2125               g_array_set_size (result, result->len + n);
2126               GetLocaleInfoW (lcid, LOCALE_SABBREVMONTHNAME1+systemtime.wMonth-1, ((wchar_t *) result->data) + result->len - n, n);
2127               g_array_set_size (result, result->len - 1);
2128               break;
2129             case 'B':
2130               n = GetLocaleInfoW (lcid, LOCALE_SMONTHNAME1+systemtime.wMonth-1, NULL, 0);
2131               g_array_set_size (result, result->len + n);
2132               GetLocaleInfoW (lcid, LOCALE_SMONTHNAME1+systemtime.wMonth-1, ((wchar_t *) result->data) + result->len - n, n);
2133               g_array_set_size (result, result->len - 1);
2134               break;
2135             case 'c':
2136               n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
2137               if (n > 0)
2138                 {
2139                   g_array_set_size (result, result->len + n);
2140                   GetDateFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
2141                   g_array_set_size (result, result->len - 1);
2142                 }
2143               g_array_append_vals (result, L" ", 1);
2144               n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
2145               if (n > 0)
2146                 {
2147                   g_array_set_size (result, result->len + n);
2148                   GetTimeFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
2149                   g_array_set_size (result, result->len - 1);
2150                 }
2151               break;
2152             case 'C':
2153               g_array_append_vals (result, digits + systemtime.wYear/1000, 1);
2154               g_array_append_vals (result, digits + (systemtime.wYear/1000)%10, 1);
2155               break;
2156             case 'd':
2157               g_array_append_vals (result, digits + systemtime.wDay/10, 1);
2158               g_array_append_vals (result, digits + systemtime.wDay%10, 1);
2159               break;
2160             case 'D':
2161               g_array_append_vals (result, digits + systemtime.wMonth/10, 1);
2162               g_array_append_vals (result, digits + systemtime.wMonth%10, 1);
2163               g_array_append_vals (result, L"/", 1);
2164               g_array_append_vals (result, digits + systemtime.wDay/10, 1);
2165               g_array_append_vals (result, digits + systemtime.wDay%10, 1);
2166               g_array_append_vals (result, L"/", 1);
2167               g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
2168               g_array_append_vals (result, digits + systemtime.wYear%10, 1);
2169               break;
2170             case 'e':
2171               if (systemtime.wDay >= 10)
2172                 g_array_append_vals (result, digits + systemtime.wDay/10, 1);
2173               else
2174                 g_array_append_vals (result, L" ", 1);
2175               g_array_append_vals (result, digits + systemtime.wDay%10, 1);
2176               break;
2177
2178               /* A GDate has no time fields, so for now we can
2179                * hardcode all time conversions into zeros (or 12 for
2180                * %I). The alternative code snippets in the #else
2181                * branches are here ready to be taken into use when
2182                * needed by a g_strftime() or g_date_and_time_format()
2183                * or whatever.
2184                */
2185             case 'H':
2186 #if 1
2187               g_array_append_vals (result, L"00", 2);
2188 #else
2189               g_array_append_vals (result, digits + systemtime.wHour/10, 1);
2190               g_array_append_vals (result, digits + systemtime.wHour%10, 1);
2191 #endif
2192               break;
2193             case 'I':
2194 #if 1
2195               g_array_append_vals (result, L"12", 2);
2196 #else
2197               if (systemtime.wHour == 0)
2198                 g_array_append_vals (result, L"12", 2);
2199               else
2200                 {
2201                   g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
2202                   g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
2203                 }
2204 #endif
2205               break;
2206             case  'j':
2207               g_array_append_vals (result, digits + (tm->tm_yday+1)/100, 1);
2208               g_array_append_vals (result, digits + ((tm->tm_yday+1)/10)%10, 1);
2209               g_array_append_vals (result, digits + (tm->tm_yday+1)%10, 1);
2210               break;
2211             case 'm':
2212               g_array_append_vals (result, digits + systemtime.wMonth/10, 1);
2213               g_array_append_vals (result, digits + systemtime.wMonth%10, 1);
2214               break;
2215             case 'M':
2216 #if 1
2217               g_array_append_vals (result, L"00", 2);
2218 #else
2219               g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
2220               g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
2221 #endif
2222               break;
2223             case 'n':
2224               g_array_append_vals (result, L"\n", 1);
2225               break;
2226             case 'p':
2227               n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
2228               if (n > 0)
2229                 {
2230                   g_array_set_size (result, result->len + n);
2231                   GetTimeFormatW (lcid, 0, &systemtime, L"tt", ((wchar_t *) result->data) + result->len - n, n);
2232                   g_array_set_size (result, result->len - 1);
2233                 }
2234               break;
2235             case 'r':
2236               /* This is a rather odd format. Hard to say what to do.
2237                * Let's always use the POSIX %I:%M:%S %p
2238                */
2239 #if 1
2240               g_array_append_vals (result, L"12:00:00", 8);
2241 #else
2242               if (systemtime.wHour == 0)
2243                 g_array_append_vals (result, L"12", 2);
2244               else
2245                 {
2246                   g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
2247                   g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
2248                 }
2249               g_array_append_vals (result, L":", 1);
2250               g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
2251               g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
2252               g_array_append_vals (result, L":", 1);
2253               g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
2254               g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
2255               g_array_append_vals (result, L" ", 1);
2256 #endif
2257               n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
2258               if (n > 0)
2259                 {
2260                   g_array_set_size (result, result->len + n);
2261                   GetTimeFormatW (lcid, 0, &systemtime, L"tt", ((wchar_t *) result->data) + result->len - n, n);
2262                   g_array_set_size (result, result->len - 1);
2263                 }
2264               break;
2265             case 'R':
2266 #if 1
2267               g_array_append_vals (result, L"00:00", 5);
2268 #else
2269               g_array_append_vals (result, digits + systemtime.wHour/10, 1);
2270               g_array_append_vals (result, digits + systemtime.wHour%10, 1);
2271               g_array_append_vals (result, L":", 1);
2272               g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
2273               g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
2274 #endif
2275               break;
2276             case 'S':
2277 #if 1
2278               g_array_append_vals (result, L"00", 2);
2279 #else
2280               g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
2281               g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
2282 #endif
2283               break;
2284             case 't':
2285               g_array_append_vals (result, L"\t", 1);
2286               break;
2287             case 'T':
2288 #if 1
2289               g_array_append_vals (result, L"00:00:00", 8);
2290 #else
2291               g_array_append_vals (result, digits + systemtime.wHour/10, 1);
2292               g_array_append_vals (result, digits + systemtime.wHour%10, 1);
2293               g_array_append_vals (result, L":", 1);
2294               g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
2295               g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
2296               g_array_append_vals (result, L":", 1);
2297               g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
2298               g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
2299 #endif
2300               break;
2301             case 'u':
2302               if (systemtime.wDayOfWeek == 0)
2303                 g_array_append_vals (result, L"7", 1);
2304               else
2305                 g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
2306               break;
2307             case 'U':
2308               n = g_date_get_sunday_week_of_year (d);
2309               g_array_append_vals (result, digits + n/10, 1);
2310               g_array_append_vals (result, digits + n%10, 1);
2311               break;
2312             case 'V':
2313               n = g_date_get_iso8601_week_of_year (d);
2314               g_array_append_vals (result, digits + n/10, 1);
2315               g_array_append_vals (result, digits + n%10, 1);
2316               break;
2317             case 'w':
2318               g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
2319               break;
2320             case 'W':
2321               n = g_date_get_monday_week_of_year (d);
2322               g_array_append_vals (result, digits + n/10, 1);
2323               g_array_append_vals (result, digits + n%10, 1);
2324               break;
2325             case 'x':
2326               n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
2327               if (n > 0)
2328                 {
2329                   g_array_set_size (result, result->len + n);
2330                   GetDateFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
2331                   g_array_set_size (result, result->len - 1);
2332                 }
2333               break;
2334             case 'X':
2335               n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
2336               if (n > 0)
2337                 {
2338                   g_array_set_size (result, result->len + n);
2339                   GetTimeFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
2340                   g_array_set_size (result, result->len - 1);
2341                 }
2342               break;
2343             case 'y':
2344               g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
2345               g_array_append_vals (result, digits + systemtime.wYear%10, 1);
2346               break;
2347             case 'Y':
2348               g_array_append_vals (result, digits + systemtime.wYear/1000, 1);
2349               g_array_append_vals (result, digits + (systemtime.wYear/100)%10, 1);
2350               g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
2351               g_array_append_vals (result, digits + systemtime.wYear%10, 1);
2352               break;
2353             case 'Z':
2354               n = GetTimeZoneInformation (&tzinfo);
2355               if (n == TIME_ZONE_ID_UNKNOWN)
2356                 ;
2357               else if (n == TIME_ZONE_ID_STANDARD)
2358                 g_array_append_vals (result, tzinfo.StandardName, wcslen (tzinfo.StandardName));
2359               else if (n == TIME_ZONE_ID_DAYLIGHT)
2360                 g_array_append_vals (result, tzinfo.DaylightName, wcslen (tzinfo.DaylightName));
2361               break;
2362             case '%':
2363               g_array_append_vals (result, L"%", 1);
2364               break;
2365             }      
2366         } 
2367       else if (c <= 0xFFFF)
2368         {
2369           wchar_t wc = c;
2370           g_array_append_vals (result, &wc, 1);
2371         }
2372       else
2373         {
2374           glong nwc;
2375           wchar_t *ws;
2376
2377           ws = g_ucs4_to_utf16 (&c, 1, NULL, &nwc, NULL);
2378           g_array_append_vals (result, ws, nwc);
2379           g_free (ws);
2380         }
2381       p = g_utf8_next_char (p);
2382     }
2383   
2384   convbuf = g_utf16_to_utf8 ((wchar_t *) result->data, result->len, NULL, &convlen, NULL);
2385   g_array_free (result, TRUE);
2386
2387   if (!convbuf)
2388     {
2389       s[0] = '\0';
2390       return 0;
2391     }
2392   
2393   if (slen <= convlen)
2394     {
2395       /* Ensure only whole characters are copied into the buffer. */
2396       gchar *end = g_utf8_find_prev_char (convbuf, convbuf + slen);
2397       g_assert (end != NULL);
2398       convlen = end - convbuf;
2399
2400       /* Return 0 because the buffer isn't large enough. */
2401       retval = 0;
2402     }
2403   else
2404     retval = convlen;
2405
2406   memcpy (s, convbuf, convlen);
2407   s[convlen] = '\0';
2408   g_free (convbuf);
2409
2410   return retval;
2411 }
2412
2413 #endif
2414
2415 /**
2416  * g_date_strftime:
2417  * @s: destination buffer
2418  * @slen: buffer size
2419  * @format: format string
2420  * @date: valid #GDate
2421  *
2422  * Generates a printed representation of the date, in a
2423  * <link linkend="setlocale">locale</link>-specific way.
2424  * Works just like the platform's C library strftime() function,
2425  * but only accepts date-related formats; time-related formats
2426  * give undefined results. Date must be valid. Unlike strftime()
2427  * (which uses the locale encoding), works on a UTF-8 format
2428  * string and stores a UTF-8 result.
2429  *
2430  * This function does not provide any conversion specifiers in
2431  * addition to those implemented by the platform's C library.
2432  * For example, don't expect that using g_date_strftime() would
2433  * make the \%F provided by the C99 strftime() work on Windows
2434  * where the C library only complies to C89.
2435  *
2436  * Returns: number of characters written to the buffer, or 0 the buffer was too small
2437  */
2438 gsize     
2439 g_date_strftime (gchar       *s, 
2440                  gsize        slen, 
2441                  const gchar *format, 
2442                  const GDate *d)
2443 {
2444   struct tm tm;
2445 #ifndef G_OS_WIN32
2446   gsize locale_format_len = 0;
2447   gchar *locale_format;
2448   gsize tmplen;
2449   gchar *tmpbuf;
2450   gsize tmpbufsize;
2451   gsize convlen = 0;
2452   gchar *convbuf;
2453   GError *error = NULL;
2454   gsize retval;
2455 #endif
2456
2457   g_return_val_if_fail (g_date_valid (d), 0);
2458   g_return_val_if_fail (slen > 0, 0); 
2459   g_return_val_if_fail (format != NULL, 0);
2460   g_return_val_if_fail (s != NULL, 0);
2461
2462   g_date_to_struct_tm (d, &tm);
2463
2464 #ifdef G_OS_WIN32
2465   if (!g_utf8_validate (format, -1, NULL))
2466     {
2467       s[0] = '\0';
2468       return 0;
2469     }
2470   return win32_strftime_helper (d, format, &tm, s, slen);
2471 #else
2472
2473   locale_format = g_locale_from_utf8 (format, -1, NULL, &locale_format_len, &error);
2474
2475   if (error)
2476     {
2477       g_warning (G_STRLOC "Error converting format to locale encoding: %s\n", error->message);
2478       g_error_free (error);
2479
2480       s[0] = '\0';
2481       return 0;
2482     }
2483
2484   tmpbufsize = MAX (128, locale_format_len * 2);
2485   while (TRUE)
2486     {
2487       tmpbuf = g_malloc (tmpbufsize);
2488
2489       /* Set the first byte to something other than '\0', to be able to
2490        * recognize whether strftime actually failed or just returned "".
2491        */
2492       tmpbuf[0] = '\1';
2493       tmplen = strftime (tmpbuf, tmpbufsize, locale_format, &tm);
2494
2495       if (tmplen == 0 && tmpbuf[0] != '\0')
2496         {
2497           g_free (tmpbuf);
2498           tmpbufsize *= 2;
2499
2500           if (tmpbufsize > 65536)
2501             {
2502               g_warning (G_STRLOC "Maximum buffer size for g_date_strftime exceeded: giving up\n");
2503               g_free (locale_format);
2504
2505               s[0] = '\0';
2506               return 0;
2507             }
2508         }
2509       else
2510         break;
2511     }
2512   g_free (locale_format);
2513
2514   convbuf = g_locale_to_utf8 (tmpbuf, tmplen, NULL, &convlen, &error);
2515   g_free (tmpbuf);
2516
2517   if (error)
2518     {
2519       g_warning (G_STRLOC "Error converting results of strftime to UTF-8: %s\n", error->message);
2520       g_error_free (error);
2521
2522       s[0] = '\0';
2523       return 0;
2524     }
2525
2526   if (slen <= convlen)
2527     {
2528       /* Ensure only whole characters are copied into the buffer.
2529        */
2530       gchar *end = g_utf8_find_prev_char (convbuf, convbuf + slen);
2531       g_assert (end != NULL);
2532       convlen = end - convbuf;
2533
2534       /* Return 0 because the buffer isn't large enough.
2535        */
2536       retval = 0;
2537     }
2538   else
2539     retval = convlen;
2540
2541   memcpy (s, convbuf, convlen);
2542   s[convlen] = '\0';
2543   g_free (convbuf);
2544
2545   return retval;
2546 #endif
2547 }