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