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