1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * SPDX-License-Identifier: LGPL-2.1-or-later
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.
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.
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/>.
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/.
32 #include "glibconfig.h"
34 #define DEBUG_MSG(x) /* */
36 /* #define DEBUG_MSG(args) g_message args ; */
52 #include "gstrfuncs.h"
53 #include "gtestutils.h"
56 #include "gutilsprivate.h"
64 * @title: Date and Time Functions
65 * @short_description: calendrical calculations and miscellaneous time stuff
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.
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).
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.
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.
105 * GLib also features #GDateTime which represents a precise time.
111 * Number of microseconds in one second (1 million).
112 * This macro is provided for code readability.
118 * @tv_usec: microseconds
120 * Represents a precise time, with seconds and microseconds.
122 * Similar to the struct timeval returned by the `gettimeofday()`
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
131 * Deprecated: 2.62: Use #GDateTime or #guint64 instead.
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
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.
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.
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,
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`.
165 * Unrelated to #GTimer.
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()
173 * Instead, do the following:
175 * |[<!-- language="C" -->
180 * gtime = (GTime)ttime;
183 * Deprecated: 2.62: This is not [Y2038-safe](https://en.wikipedia.org/wiki/Year_2038_problem).
184 * Use #GDateTime or #time_t instead.
190 * @G_DATE_MONTH: a month
191 * @G_DATE_YEAR: a year
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.
200 * Integer representing a day of the month; between 1 and 31.
202 * The %G_DATE_BAD_DAY value represents an invalid day of the month.
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
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
221 * Enumeration representing a month; values are %G_DATE_JANUARY,
222 * %G_DATE_FEBRUARY, etc. %G_DATE_BAD_MONTH is the invalid value.
228 * Integer type representing a year.
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.
234 * The year is represented with four digits.
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
248 * Enumeration representing a day of the week; %G_DATE_MONDAY,
249 * %G_DATE_TUESDAY, etc. %G_DATE_BAD_WEEKDAY is an invalid weekday.
255 * Represents an invalid #GDateDay.
261 * Represents an invalid Julian day number.
267 * Represents an invalid year.
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().
278 * Returns: a newly-allocated #GDate
283 GDate *d = g_new0 (GDate, 1); /* happily, 0 is the invalid flag for everything. */
290 * @day: day of the month
291 * @month: month of the year
294 * Create a new #GDate representing the given day-month-year triplet.
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
300 * Returns: (transfer full) (not nullable): a newly-allocated #GDate
301 * initialized with @day, @month, and @year
304 g_date_new_dmy (GDateDay day,
309 g_return_val_if_fail (g_date_valid_dmy (day, m, y), NULL);
311 d = g_new (GDate, 1);
320 g_assert (g_date_valid (d));
327 * @julian_day: days since January 1, Year 1
329 * Create a new #GDate representing the given Julian date.
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
335 * Returns: (transfer full) (not nullable): a newly-allocated #GDate initialized
339 g_date_new_julian (guint32 julian_day)
342 g_return_val_if_fail (g_date_valid_julian (julian_day), NULL);
344 d = g_new (GDate, 1);
349 d->julian_days = julian_day;
351 g_assert (g_date_valid (d));
358 * @date: a #GDate to free
360 * Frees a #GDate returned from g_date_new().
363 g_date_free (GDate *date)
365 g_return_if_fail (date != NULL);
372 * @date: a #GDate to copy
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.
378 * Returns: (transfer full): a newly-allocated #GDate initialized from @date
383 g_date_copy (const GDate *date)
386 g_return_val_if_fail (date != NULL, NULL);
388 if (g_date_valid (date))
389 res = g_date_new_julian (g_date_get_julian (date));
401 * @date: a #GDate to check
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.
407 * Returns: Whether the date is valid
410 g_date_valid (const GDate *d)
412 g_return_val_if_fail (d != NULL, FALSE);
414 return (d->julian || d->dmy);
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 */
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 }
430 * g_date_valid_month:
433 * Returns %TRUE if the month value is valid. The 12 #GDateMonth
434 * enumeration values are the only valid months.
436 * Returns: %TRUE if the month is valid
439 g_date_valid_month (GDateMonth m)
441 return (((gint) m > G_DATE_BAD_MONTH) && ((gint) m < 13));
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.
451 * Returns: %TRUE if the year is valid
454 g_date_valid_year (GDateYear y)
456 return ( y > G_DATE_BAD_YEAR );
463 * Returns %TRUE if the day of the month is valid (a day is valid if it's
464 * between 1 and 31 inclusive).
466 * Returns: %TRUE if the day is valid
470 g_date_valid_day (GDateDay d)
472 return ( (d > G_DATE_BAD_DAY) && (d < 32) );
476 * g_date_valid_weekday:
479 * Returns %TRUE if the weekday is valid. The seven #GDateWeekday enumeration
480 * values are the only valid weekdays.
482 * Returns: %TRUE if the weekday is valid
485 g_date_valid_weekday (GDateWeekday w)
487 return (((gint) w > G_DATE_BAD_WEEKDAY) && ((gint) w < 8));
491 * g_date_valid_julian:
492 * @julian_date: Julian day to check
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.
497 * Returns: %TRUE if the Julian day is valid
500 g_date_valid_julian (guint32 j)
502 return (j > G_DATE_BAD_JULIAN);
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).
515 * Returns: %TRUE if the date is a valid one
518 g_date_valid_dmy (GDateDay d,
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) &&
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])) );
533 /* "Julian days" just means an absolute number of days, where Day 1 ==
537 g_date_update_julian (const GDate *const_d)
539 GDate *d = (GDate *) const_d;
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));
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
555 year = d->year - 1; /* we know d->year > 0 since it's valid */
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 */
562 idx = g_date_is_leap_year (d->year) ? 1 : 0;
564 d->julian_days += days_in_year[idx][d->month] + d->day;
566 g_return_if_fail (g_date_valid_julian (d->julian_days));
572 g_date_update_dmy (const GDate *const_d)
574 GDate *d = (GDate *) const_d;
579 guint32 A, B, C, D, E, M;
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));
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.
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.
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;
601 m = M + 3 - (12*(M/10));
602 day = E - (153*M + 2)/5;
603 y = 100 * B + D - 4800 + (M/10);
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);
619 * g_date_get_weekday:
622 * Returns the day of the week for a #GDate. The date must be valid.
624 * Returns: day of the week as a #GDateWeekday.
627 g_date_get_weekday (const GDate *d)
629 g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_WEEKDAY);
632 g_date_update_julian (d);
634 g_return_val_if_fail (d->julian, G_DATE_BAD_WEEKDAY);
636 return ((d->julian_days - 1) % 7) + 1;
641 * @date: a #GDate to get the month from
643 * Returns the month of the year. The date must be valid.
645 * Returns: month of the year as a #GDateMonth
648 g_date_get_month (const GDate *d)
650 g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_MONTH);
653 g_date_update_dmy (d);
655 g_return_val_if_fail (d->dmy, G_DATE_BAD_MONTH);
664 * Returns the year of a #GDate. The date must be valid.
666 * Returns: year in which the date falls
669 g_date_get_year (const GDate *d)
671 g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_YEAR);
674 g_date_update_dmy (d);
676 g_return_val_if_fail (d->dmy, G_DATE_BAD_YEAR);
683 * @date: a #GDate to extract the day of the month from
685 * Returns the day of the month. The date must be valid.
687 * Returns: day of the month
690 g_date_get_day (const GDate *d)
692 g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_DAY);
695 g_date_update_dmy (d);
697 g_return_val_if_fail (d->dmy, G_DATE_BAD_DAY);
704 * @date: a #GDate to extract the Julian day from
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.
711 * Returns: Julian day
714 g_date_get_julian (const GDate *d)
716 g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_JULIAN);
719 g_date_update_julian (d);
721 g_return_val_if_fail (d->julian, G_DATE_BAD_JULIAN);
723 return d->julian_days;
727 * g_date_get_day_of_year:
728 * @date: a #GDate to extract day of year from
730 * Returns the day of the year, where Jan 1 is the first day of the
731 * year. The date must be valid.
733 * Returns: day of the year
736 g_date_get_day_of_year (const GDate *d)
740 g_return_val_if_fail (g_date_valid (d), 0);
743 g_date_update_dmy (d);
745 g_return_val_if_fail (d->dmy, 0);
747 idx = g_date_is_leap_year (d->year) ? 1 : 0;
749 return (days_in_year[idx][d->month] + d->day);
753 * g_date_get_monday_week_of_year:
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.
760 * Returns: week of the year
763 g_date_get_monday_week_of_year (const GDate *d)
769 g_return_val_if_fail (g_date_valid (d), 0);
772 g_date_update_dmy (d);
774 g_return_val_if_fail (d->dmy, 0);
776 g_date_clear (&first, 1);
778 g_date_set_dmy (&first, 1, 1, d->year);
780 wd = g_date_get_weekday (&first) - 1; /* make Monday day 0 */
781 day = g_date_get_day_of_year (d) - 1;
783 return ((day + wd)/7U + (wd == 0 ? 1 : 0));
787 * g_date_get_sunday_week_of_year:
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.
794 * Returns: week number
797 g_date_get_sunday_week_of_year (const GDate *d)
803 g_return_val_if_fail (g_date_valid (d), 0);
806 g_date_update_dmy (d);
808 g_return_val_if_fail (d->dmy, 0);
810 g_date_clear (&first, 1);
812 g_date_set_dmy (&first, 1, 1, d->year);
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;
818 return ((day + wd)/7U + (wd == 0 ? 1 : 0));
822 * g_date_get_iso8601_week_of_year:
823 * @date: a valid #GDate
825 * Returns the week of the year, where weeks are interpreted according
828 * Returns: ISO 8601 week number of the year.
833 g_date_get_iso8601_week_of_year (const GDate *d)
835 guint j, d4, L, d1, w;
837 g_return_val_if_fail (g_date_valid (d), 0);
840 g_date_update_julian (d);
842 g_return_val_if_fail (d->julian, 0);
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.
848 j = d->julian_days + 1721425;
849 d4 = (j + 31741 - (j % 7)) % 146097 % 36524 % 1461;
851 d1 = ((d4 - L) % 365) + L;
858 * g_date_days_between:
859 * @date1: the first date
860 * @date2: the second date
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.
866 * Returns: the number of days between @date1 and @date2
869 g_date_days_between (const GDate *d1,
872 g_return_val_if_fail (g_date_valid (d1), 0);
873 g_return_val_if_fail (g_date_valid (d2), 0);
875 return (gint)g_date_get_julian (d2) - (gint)g_date_get_julian (d1);
880 * @date: pointer to one or more dates to clear
881 * @n_dates: number of dates to clear
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().
889 g_date_clear (GDate *d, guint ndates)
891 g_return_if_fail (d != NULL);
892 g_return_if_fail (ndates != 0);
894 memset (d, 0x0, ndates*sizeof (GDate));
897 G_LOCK_DEFINE_STATIC (g_date_global);
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. :-)
904 static gchar *long_month_names[13] =
909 static gchar *long_month_names_alternative[13] =
914 static gchar *short_month_names[13] =
919 static gchar *short_month_names_alternative[13] =
924 /* This tells us if we need to update the parse info */
925 static gchar *current_locale = NULL;
927 /* order of these in the current locale */
928 static GDateDMY dmy_order[3] =
930 G_DATE_DAY, G_DATE_MONTH, G_DATE_YEAR
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.
938 static const GDateYear twodigit_start_year = 1930;
940 /* It is impossible to enter a year between 1 AD and 99 AD with this
943 static gboolean using_twodigit_years = FALSE;
945 /* Adjustment of locale era to AD, non-zero means using locale era
947 static gint locale_era_adjust = 0;
949 struct _GDateParseTokens {
955 typedef struct _GDateParseTokens GDateParseTokens;
957 static inline gboolean
958 update_month_match (gsize *longest,
959 const gchar *haystack,
967 length = strlen (needle);
968 if (*longest >= length)
971 if (strstr (haystack, needle) == NULL)
980 /* HOLDS: g_date_global_lock */
982 g_date_fill_parse_tokens (const gchar *str, GDateParseTokens *pt)
984 gchar num[4][NUM_LEN+1];
988 /* We count 4, but store 3; so we can give an error
991 num[0][0] = num[1][0] = num[2][0] = num[3][0] = '\0';
993 s = (const guchar *) str;
995 while (*s && pt->num_ints < 4)
999 while (*s && g_ascii_isdigit (*s) && i < NUM_LEN)
1001 num[pt->num_ints][i] = *s;
1008 num[pt->num_ints][i] = '\0';
1012 if (*s == '\0') break;
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;
1021 pt->month = G_DATE_BAD_MONTH;
1023 if (pt->num_ints < 3)
1029 casefold = g_utf8_casefold (str, -1);
1030 normalized = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
1033 for (i = 1; i < 13; ++i)
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".
1044 if (update_month_match (&longest, normalized, long_month_names[i]))
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".
1052 if (update_month_match (&longest, normalized, long_month_names_alternative[i]))
1055 /* Differences between abbreviated nominative and abbreviated
1056 * genitive month names are visible in very few languages but
1057 * let's handle them.
1059 if (update_month_match (&longest, normalized, short_month_names[i]))
1062 if (update_month_match (&longest, normalized, short_month_names_alternative[i]))
1066 g_free (normalized);
1070 /* HOLDS: g_date_global_lock */
1072 g_date_prepare_to_parse (const gchar *str,
1073 GDateParseTokens *pt)
1075 const gchar *locale = setlocale (LC_TIME, NULL);
1076 gboolean recompute_localeinfo = FALSE;
1079 g_return_if_fail (locale != NULL); /* should not happen */
1081 g_date_clear (&d, 1); /* clear for scratch use */
1083 if ( (current_locale == NULL) || (strcmp (locale, current_locale) != 0) )
1084 recompute_localeinfo = TRUE; /* Uh, there used to be a reason for the temporary */
1086 if (recompute_localeinfo)
1089 GDateParseTokens testpt;
1092 g_free (current_locale); /* still works if current_locale == NULL */
1094 current_locale = g_strdup (locale);
1096 short_month_names[0] = "Error";
1097 long_month_names[0] = "Error";
1103 g_date_set_dmy (&d, 1, i, 1976);
1105 g_return_if_fail (g_date_valid (&d));
1107 g_date_strftime (buf, 127, "%b", &d);
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);
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);
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);
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);
1135 /* Determine DMY order */
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);
1141 g_date_strftime (buf, 127, "%x", &d);
1143 g_date_fill_parse_tokens (buf, &testpt);
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;
1152 while (i < testpt.num_ints)
1154 switch (testpt.n[i])
1157 dmy_order[i] = G_DATE_MONTH;
1160 dmy_order[i] = G_DATE_DAY;
1163 using_twodigit_years = TRUE;
1166 dmy_order[i] = G_DATE_YEAR;
1169 /* assume locale era */
1170 locale_era_adjust = 1976 - testpt.n[i];
1171 dmy_order[i] = G_DATE_YEAR;
1177 #if defined(G_ENABLE_DEBUG) && 0
1178 DEBUG_MSG (("**GDate prepared a new set of locale-specific parse rules."));
1182 DEBUG_MSG ((" %s %s", long_month_names[i], short_month_names[i]));
1185 DEBUG_MSG (("Alternative month names:"));
1189 DEBUG_MSG ((" %s %s", long_month_names_alternative[i], short_month_names_alternative[i]));
1192 if (using_twodigit_years)
1194 DEBUG_MSG (("**Using twodigit years with cutoff year: %u", twodigit_start_year));
1201 switch (dmy_order[i])
1204 strings[i] = "Month";
1207 strings[i] = "Year";
1218 DEBUG_MSG (("**Order: %s, %s, %s", strings[0], strings[1], strings[2]));
1219 DEBUG_MSG (("**Sample date in this locale: '%s'", buf));
1224 g_date_fill_parse_tokens (str, pt);
1228 convert_twodigit_year (guint y)
1230 if (using_twodigit_years && y < 100)
1232 guint two = twodigit_start_year % 100;
1233 guint century = (twodigit_start_year / 100) * 100;
1245 * @date: a #GDate to fill in
1246 * @str: string to parse
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.
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
1261 g_date_set_parse (GDate *d,
1264 GDateParseTokens pt;
1265 guint m = G_DATE_BAD_MONTH, day = G_DATE_BAD_DAY, y = G_DATE_BAD_YEAR;
1268 g_return_if_fail (d != NULL);
1271 g_date_clear (d, 1);
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);
1279 /* The input has to be valid UTF-8. */
1280 if (!g_utf8_validate_len (str, str_len, NULL))
1283 G_LOCK (g_date_global);
1285 g_date_prepare_to_parse (str, &pt);
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));
1291 if (pt.num_ints == 4)
1293 G_UNLOCK (g_date_global);
1294 return; /* presumably a typo; bail out. */
1297 if (pt.num_ints > 1)
1302 g_assert (pt.num_ints < 4); /* i.e., it is 2 or 3 */
1304 while (i < pt.num_ints && j < 3)
1306 switch (dmy_order[j])
1310 if (pt.num_ints == 2 && pt.month != G_DATE_BAD_MONTH)
1313 ++j; /* skip months, but don't skip this number */
1322 if (pt.num_ints == 2 && pt.month == G_DATE_BAD_MONTH)
1325 ++j; /* skip days, since we may have month/year */
1335 if (locale_era_adjust != 0)
1337 y += locale_era_adjust;
1340 y = convert_twodigit_year (y);
1352 if (pt.num_ints == 3 && !g_date_valid_dmy (day, m, y))
1354 /* Try YYYY MM DD */
1359 if (using_twodigit_years && y < 100)
1360 y = G_DATE_BAD_YEAR; /* avoids ambiguity */
1362 else if (pt.num_ints == 2)
1364 if (m == G_DATE_BAD_MONTH && pt.month != G_DATE_BAD_MONTH)
1368 else if (pt.num_ints == 1)
1370 if (pt.month != G_DATE_BAD_MONTH)
1372 /* Month name and year? */
1379 /* Try yyyymmdd and yymmdd */
1381 m = (pt.n[0]/100) % 100;
1382 day = pt.n[0] % 100;
1385 y = convert_twodigit_year (y);
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))
1398 #ifdef G_ENABLE_DEBUG
1401 DEBUG_MSG (("Rejected DMY %u %u %u", day, m, y));
1404 G_UNLOCK (g_date_global);
1408 _g_localtime (time_t timet, struct tm *out_tm)
1410 gboolean success = TRUE;
1412 #ifdef HAVE_LOCALTIME_R
1413 if (!localtime_r (&timet, out_tm))
1417 struct tm *ptm = localtime (&timet);
1421 /* Happens at least in Microsoft's C library if you pass a
1427 memcpy (out_tm, ptm, sizeof (struct tm));
1435 * g_date_set_time_t:
1437 * @timet: time_t value to set
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.
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);
1454 g_date_set_time_t (GDate *date,
1460 g_return_if_fail (date != NULL);
1462 success = _g_localtime (timet, &tm);
1465 /* Still set a default date, 2000-01-01.
1467 * We may assert out below. */
1473 date->julian = FALSE;
1475 date->month = tm.tm_mon + 1;
1476 date->day = tm.tm_mday;
1477 date->year = tm.tm_year + 1900;
1479 g_return_if_fail (g_date_valid_dmy (date->day, date->month, date->year));
1483 #ifndef G_DISABLE_CHECKS
1485 g_return_if_fail_warning (G_LOG_DOMAIN, "g_date_set_time", "localtime() == NULL");
1493 * @time_: #GTime value to set.
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.
1498 * Deprecated: 2.10: Use g_date_set_time_t() instead.
1500 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
1502 g_date_set_time (GDate *date,
1505 g_date_set_time_t (date, (time_t) time_);
1507 G_GNUC_END_IGNORE_DEPRECATIONS
1510 * g_date_set_time_val:
1512 * @timeval: #GTimeVal value to set
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.
1518 * The time to date conversion is done using the user's current timezone.
1521 * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use g_date_set_time_t()
1524 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
1526 g_date_set_time_val (GDate *date,
1529 g_date_set_time_t (date, (time_t) timeval->tv_sec);
1531 G_GNUC_END_IGNORE_DEPRECATIONS
1536 * @month: month to set
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.
1542 g_date_set_month (GDate *d,
1545 g_return_if_fail (d != NULL);
1546 g_return_if_fail (g_date_valid_month (m));
1548 if (d->julian && !d->dmy) g_date_update_dmy(d);
1553 if (g_date_valid_dmy (d->day, d->month, d->year))
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.
1568 g_date_set_day (GDate *d,
1571 g_return_if_fail (d != NULL);
1572 g_return_if_fail (g_date_valid_day (day));
1574 if (d->julian && !d->dmy) g_date_update_dmy(d);
1579 if (g_date_valid_dmy (d->day, d->month, d->year))
1588 * @year: year to set
1590 * Sets the year for a #GDate. If the resulting day-month-year
1591 * triplet is invalid, the date will be invalid.
1594 g_date_set_year (GDate *d,
1597 g_return_if_fail (d != NULL);
1598 g_return_if_fail (g_date_valid_year (y));
1600 if (d->julian && !d->dmy) g_date_update_dmy(d);
1605 if (g_date_valid_dmy (d->day, d->month, d->year))
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
1624 g_date_set_dmy (GDate *d,
1629 g_return_if_fail (d != NULL);
1630 g_return_if_fail (g_date_valid_dmy (day, m, y));
1642 * g_date_set_julian:
1644 * @julian_date: Julian day number (days since January 1, Year 1)
1646 * Sets the value of a #GDate from a Julian day number.
1649 g_date_set_julian (GDate *d,
1652 g_return_if_fail (d != NULL);
1653 g_return_if_fail (g_date_valid_julian (j));
1661 * g_date_is_first_of_month:
1662 * @date: a #GDate to check
1664 * Returns %TRUE if the date is on the first of a month.
1665 * The date must be valid.
1667 * Returns: %TRUE if the date is the first of the month
1670 g_date_is_first_of_month (const GDate *d)
1672 g_return_val_if_fail (g_date_valid (d), FALSE);
1675 g_date_update_dmy (d);
1677 g_return_val_if_fail (d->dmy, FALSE);
1679 if (d->day == 1) return TRUE;
1684 * g_date_is_last_of_month:
1685 * @date: a #GDate to check
1687 * Returns %TRUE if the date is the last day of the month.
1688 * The date must be valid.
1690 * Returns: %TRUE if the date is the last day of the month
1693 g_date_is_last_of_month (const GDate *d)
1697 g_return_val_if_fail (g_date_valid (d), FALSE);
1700 g_date_update_dmy (d);
1702 g_return_val_if_fail (d->dmy, FALSE);
1704 idx = g_date_is_leap_year (d->year) ? 1 : 0;
1706 if (d->day == days_in_months[idx][d->month]) return TRUE;
1712 * @date: a #GDate to increment
1713 * @n_days: number of days to move the date forward
1715 * Increments a date some number of days.
1716 * To move forward by weeks, add weeks*7 days.
1717 * The date must be valid.
1720 g_date_add_days (GDate *d,
1723 g_return_if_fail (g_date_valid (d));
1726 g_date_update_julian (d);
1728 g_return_if_fail (d->julian);
1729 g_return_if_fail (ndays <= G_MAXUINT32 - d->julian_days);
1731 d->julian_days += ndays;
1736 * g_date_subtract_days:
1737 * @date: a #GDate to decrement
1738 * @n_days: number of days to move
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.
1745 g_date_subtract_days (GDate *d,
1748 g_return_if_fail (g_date_valid (d));
1751 g_date_update_julian (d);
1753 g_return_if_fail (d->julian);
1754 g_return_if_fail (d->julian_days > ndays);
1756 d->julian_days -= ndays;
1761 * g_date_add_months:
1762 * @date: a #GDate to increment
1763 * @n_months: number of months to move forward
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.
1772 g_date_add_months (GDate *d,
1775 guint years, months;
1778 g_return_if_fail (g_date_valid (d));
1781 g_date_update_dmy (d);
1783 g_return_if_fail (d->dmy != 0);
1784 g_return_if_fail (nmonths <= G_MAXUINT - (d->month - 1));
1786 nmonths += d->month - 1;
1789 months = nmonths%12;
1791 g_return_if_fail (years <= (guint) (G_MAXUINT16 - d->year));
1793 d->month = months + 1;
1796 idx = g_date_is_leap_year (d->year) ? 1 : 0;
1798 if (d->day > days_in_months[idx][d->month])
1799 d->day = days_in_months[idx][d->month];
1803 g_return_if_fail (g_date_valid (d));
1807 * g_date_subtract_months:
1808 * @date: a #GDate to decrement
1809 * @n_months: number of months to move
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.
1817 g_date_subtract_months (GDate *d,
1820 guint years, months;
1823 g_return_if_fail (g_date_valid (d));
1826 g_date_update_dmy (d);
1828 g_return_if_fail (d->dmy != 0);
1831 months = nmonths%12;
1833 g_return_if_fail (d->year > years);
1837 if (d->month > months) d->month -= months;
1841 d->month = 12 - months;
1845 idx = g_date_is_leap_year (d->year) ? 1 : 0;
1847 if (d->day > days_in_months[idx][d->month])
1848 d->day = days_in_months[idx][d->month];
1852 g_return_if_fail (g_date_valid (d));
1857 * @date: a #GDate to increment
1858 * @n_years: number of years to move forward
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.
1866 g_date_add_years (GDate *d,
1869 g_return_if_fail (g_date_valid (d));
1872 g_date_update_dmy (d);
1874 g_return_if_fail (d->dmy != 0);
1875 g_return_if_fail (nyears <= (guint) (G_MAXUINT16 - d->year));
1879 if (d->month == 2 && d->day == 29)
1881 if (!g_date_is_leap_year (d->year))
1889 * g_date_subtract_years:
1890 * @date: a #GDate to decrement
1891 * @n_years: number of years to move
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
1900 g_date_subtract_years (GDate *d,
1903 g_return_if_fail (g_date_valid (d));
1906 g_date_update_dmy (d);
1908 g_return_if_fail (d->dmy != 0);
1909 g_return_if_fail (d->year > nyears);
1913 if (d->month == 2 && d->day == 29)
1915 if (!g_date_is_leap_year (d->year))
1923 * g_date_is_leap_year:
1924 * @year: year to check
1926 * Returns %TRUE if the year is a leap year.
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.
1933 * Returns: %TRUE if the year is a leap year
1936 g_date_is_leap_year (GDateYear year)
1938 g_return_val_if_fail (g_date_valid_year (year), FALSE);
1940 return ( (((year % 4) == 0) && ((year % 100) != 0)) ||
1941 (year % 400) == 0 );
1945 * g_date_get_days_in_month:
1949 * Returns the number of days in a month, taking leap
1950 * years into account.
1952 * Returns: number of days in @month during the @year
1955 g_date_get_days_in_month (GDateMonth month,
1960 g_return_val_if_fail (g_date_valid_year (year), 0);
1961 g_return_val_if_fail (g_date_valid_month (month), 0);
1963 idx = g_date_is_leap_year (year) ? 1 : 0;
1965 return days_in_months[idx][month];
1969 * g_date_get_monday_weeks_in_year:
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.)
1980 * Returns: number of Mondays in the year
1983 g_date_get_monday_weeks_in_year (GDateYear year)
1987 g_return_val_if_fail (g_date_valid_year (year), 0);
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))
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;
2005 * g_date_get_sunday_weeks_in_year:
2006 * @year: year to count weeks in
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.)
2016 * Returns: the number of weeks in @year
2019 g_date_get_sunday_weeks_in_year (GDateYear year)
2023 g_return_val_if_fail (g_date_valid_year (year), 0);
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))
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;
2042 * @lhs: first date to compare
2043 * @rhs: second date to compare
2045 * qsort()-style comparison function for dates.
2046 * Both dates must be valid.
2048 * Returns: 0 for equal, less than zero if @lhs is less than @rhs,
2049 * greater than zero if @lhs is greater than @rhs
2052 g_date_compare (const GDate *lhs,
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);
2060 /* Remember the self-comparison case! I think it works right now. */
2064 if (lhs->julian && rhs->julian)
2066 if (lhs->julian_days < rhs->julian_days) return -1;
2067 else if (lhs->julian_days > rhs->julian_days) return 1;
2070 else if (lhs->dmy && rhs->dmy)
2072 if (lhs->year < rhs->year) return -1;
2073 else if (lhs->year > rhs->year) return 1;
2076 if (lhs->month < rhs->month) return -1;
2077 else if (lhs->month > rhs->month) return 1;
2080 if (lhs->day < rhs->day) return -1;
2081 else if (lhs->day > rhs->day) return 1;
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);
2097 return 0; /* warnings */
2101 * g_date_to_struct_tm:
2102 * @date: a #GDate to set the struct tm from
2103 * @tm: (not nullable): struct tm to fill
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.
2109 g_date_to_struct_tm (const GDate *d,
2114 g_return_if_fail (g_date_valid (d));
2115 g_return_if_fail (tm != NULL);
2118 g_date_update_dmy (d);
2120 g_return_if_fail (d->dmy != 0);
2122 /* zero all the irrelevant fields to be sure they're valid */
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.
2130 memset (tm, 0x0, sizeof (struct tm));
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 */
2136 day = g_date_get_weekday (d);
2137 if (day == 7) day = 0; /* struct tm wants days since Sunday, so Sunday is 0 */
2139 tm->tm_wday = (int)day;
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" */
2147 * @date: a #GDate to clamp
2148 * @min_date: minimum accepted value for @date
2149 * @max_date: maximum accepted value for @date
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.
2158 g_date_clamp (GDate *date,
2159 const GDate *min_date,
2160 const GDate *max_date)
2162 g_return_if_fail (g_date_valid (date));
2164 if (min_date != NULL)
2165 g_return_if_fail (g_date_valid (min_date));
2167 if (max_date != NULL)
2168 g_return_if_fail (g_date_valid (max_date));
2170 if (min_date != NULL && max_date != NULL)
2171 g_return_if_fail (g_date_compare (min_date, max_date) <= 0);
2173 if (min_date && g_date_compare (date, min_date) < 0)
2176 if (max_date && g_date_compare (max_date, date) < 0)
2182 * @date1: the first date
2183 * @date2: the second date
2185 * Checks if @date1 is less than or equal to @date2,
2186 * and swap the values if this is not the case.
2189 g_date_order (GDate *date1,
2192 g_return_if_fail (g_date_valid (date1));
2193 g_return_if_fail (g_date_valid (date2));
2195 if (g_date_compare (date1, date2) > 0)
2205 append_month_name (GArray *result,
2207 SYSTEMTIME *systemtime,
2208 gboolean abbreviated,
2209 gboolean alternative)
2217 base = abbreviated ? LOCALE_SABBREVMONTHNAME1 : LOCALE_SMONTHNAME1;
2218 n = GetLocaleInfoW (lcid, base + systemtime->wMonth - 1, NULL, 0);
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)
2227 g_array_set_size (result, result->len - 1);
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.
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.
2238 lpFormat = abbreviated ? L"ddMMM" : L"ddMMMM";
2239 n = GetDateFormatW (lcid, 0, systemtime, lpFormat, NULL, 0);
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)
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
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);
2262 win32_strftime_helper (const GDate *d,
2263 const gchar *format,
2264 const struct tm *tm,
2268 SYSTEMTIME systemtime;
2269 TIME_ZONE_INFORMATION tzinfo;
2274 gunichar c, modifier;
2275 const wchar_t digits[] = L"0123456789";
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;
2289 lcid = GetThreadLocale ();
2290 result = g_array_sized_new (FALSE, FALSE, sizeof (wchar_t), MAX (128, strlen (format) * 2));
2295 c = g_utf8_get_char (p);
2298 p = g_utf8_next_char (p);
2302 g_array_free (result, TRUE);
2308 c = g_utf8_get_char (p);
2309 if (c == 'E' || c == 'O')
2311 /* "%OB", "%Ob", and "%Oh" are supported, ignore other modified
2312 * conversion specifiers for now.
2315 p = g_utf8_next_char (p);
2319 g_array_free (result, TRUE);
2324 c = g_utf8_get_char (p);
2330 if (systemtime.wDayOfWeek == 0)
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);
2340 if (systemtime.wDayOfWeek == 0)
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);
2351 if (!append_month_name (result, lcid, &systemtime, TRUE, modifier == 'O'))
2353 /* Ignore the error; this placeholder will be replaced with nothing */
2357 if (!append_month_name (result, lcid, &systemtime, FALSE, modifier == 'O'))
2359 /* Ignore the error; this placeholder will be replaced with nothing */
2363 n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
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);
2370 g_array_append_vals (result, L" ", 1);
2371 n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
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);
2380 g_array_append_vals (result, digits + systemtime.wYear/1000, 1);
2381 g_array_append_vals (result, digits + (systemtime.wYear/1000)%10, 1);
2384 g_array_append_vals (result, digits + systemtime.wDay/10, 1);
2385 g_array_append_vals (result, digits + systemtime.wDay%10, 1);
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);
2398 if (systemtime.wDay >= 10)
2399 g_array_append_vals (result, digits + systemtime.wDay/10, 1);
2401 g_array_append_vals (result, L" ", 1);
2402 g_array_append_vals (result, digits + systemtime.wDay%10, 1);
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()
2414 g_array_append_vals (result, L"00", 2);
2416 g_array_append_vals (result, digits + systemtime.wHour/10, 1);
2417 g_array_append_vals (result, digits + systemtime.wHour%10, 1);
2422 g_array_append_vals (result, L"12", 2);
2424 if (systemtime.wHour == 0)
2425 g_array_append_vals (result, L"12", 2);
2428 g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
2429 g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
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);
2439 g_array_append_vals (result, digits + systemtime.wMonth/10, 1);
2440 g_array_append_vals (result, digits + systemtime.wMonth%10, 1);
2444 g_array_append_vals (result, L"00", 2);
2446 g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
2447 g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
2451 g_array_append_vals (result, L"\n", 1);
2454 n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
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);
2463 /* This is a rather odd format. Hard to say what to do.
2464 * Let's always use the POSIX %I:%M:%S %p
2467 g_array_append_vals (result, L"12:00:00", 8);
2469 if (systemtime.wHour == 0)
2470 g_array_append_vals (result, L"12", 2);
2473 g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
2474 g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
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);
2484 n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
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);
2494 g_array_append_vals (result, L"00:00", 5);
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);
2505 g_array_append_vals (result, L"00", 2);
2507 g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
2508 g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
2512 g_array_append_vals (result, L"\t", 1);
2516 g_array_append_vals (result, L"00:00:00", 8);
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);
2529 if (systemtime.wDayOfWeek == 0)
2530 g_array_append_vals (result, L"7", 1);
2532 g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
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);
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);
2545 g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
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);
2553 n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
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);
2562 n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
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);
2571 g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
2572 g_array_append_vals (result, digits + systemtime.wYear%10, 1);
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);
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));
2588 g_array_append_vals (result, L"%", 1);
2592 else if (c <= 0xFFFF)
2595 g_array_append_vals (result, &wc, 1);
2602 ws = g_ucs4_to_utf16 (&c, 1, NULL, &nwc, NULL);
2603 g_array_append_vals (result, ws, nwc);
2606 p = g_utf8_next_char (p);
2609 convbuf = g_utf16_to_utf8 ((wchar_t *) result->data, result->len, NULL, &convlen, NULL);
2610 g_array_free (result, TRUE);
2618 g_assert (convlen >= 0);
2619 if ((gsize) convlen >= slen)
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;
2626 /* Return 0 because the buffer isn't large enough. */
2632 memcpy (s, convbuf, convlen);
2643 * @s: destination buffer
2644 * @slen: buffer size
2645 * @format: format string
2646 * @date: valid #GDate
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.
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.
2662 * Returns: number of characters written to the buffer, or 0 the buffer was too small
2664 #pragma GCC diagnostic push
2665 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2668 g_date_strftime (gchar *s,
2670 const gchar *format,
2675 gsize locale_format_len = 0;
2676 gchar *locale_format;
2682 GError *error = NULL;
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);
2691 g_date_to_struct_tm (d, &tm);
2694 if (!g_utf8_validate (format, -1, NULL))
2699 return win32_strftime_helper (d, format, &tm, s, slen);
2702 locale_format = g_locale_from_utf8 (format, -1, NULL, &locale_format_len, &error);
2706 g_warning (G_STRLOC "Error converting format to locale encoding: %s", error->message);
2707 g_error_free (error);
2713 tmpbufsize = MAX (128, locale_format_len * 2);
2716 tmpbuf = g_malloc (tmpbufsize);
2718 /* Set the first byte to something other than '\0', to be able to
2719 * recognize whether strftime actually failed or just returned "".
2722 tmplen = strftime (tmpbuf, tmpbufsize, locale_format, &tm);
2724 if (tmplen == 0 && tmpbuf[0] != '\0')
2729 if (tmpbufsize > 65536)
2731 g_warning (G_STRLOC "Maximum buffer size for g_date_strftime exceeded: giving up");
2732 g_free (locale_format);
2741 g_free (locale_format);
2743 convbuf = g_locale_to_utf8 (tmpbuf, tmplen, NULL, &convlen, &error);
2748 g_warning (G_STRLOC "Error converting results of strftime to UTF-8: %s", error->message);
2749 g_error_free (error);
2751 g_assert (convbuf == NULL);
2757 if (slen <= convlen)
2759 /* Ensure only whole characters are copied into the buffer.
2761 gchar *end = g_utf8_find_prev_char (convbuf, convbuf + slen);
2762 g_assert (end != NULL);
2763 convlen = end - convbuf;
2765 /* Return 0 because the buffer isn't large enough.
2772 memcpy (s, convbuf, convlen);
2780 #pragma GCC diagnostic pop