Merge branch 'test-ip_mreq_source-android-only' into 'master'
[glib.git] / glib / gdate.c
blob6e163b8a7ea0eeb630b6c03c996e31bf45827385
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
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.
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.
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/>.
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/.
25 /*
26 * MT safe
29 #include "config.h"
30 #include "glibconfig.h"
32 #define DEBUG_MSG(x) /* */
33 #ifdef G_ENABLE_DEBUG
34 /* #define DEBUG_MSG(args) g_message args ; */
35 #endif
37 #include <time.h>
38 #include <string.h>
39 #include <stdlib.h>
40 #include <locale.h>
42 #ifdef G_OS_WIN32
43 #include <windows.h>
44 #endif
46 #include "gdate.h"
48 #include "gconvert.h"
49 #include "gmem.h"
50 #include "gstrfuncs.h"
51 #include "gtestutils.h"
52 #include "gthread.h"
53 #include "gunicode.h"
55 #ifdef G_OS_WIN32
56 #include "garray.h"
57 #endif
59 /**
60 * SECTION:date
61 * @title: Date and Time Functions
62 * @short_description: calendrical calculations and miscellaneous time stuff
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.
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).
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 to a sane state by
87 * calling g_date_clear(). A cleared date is sane; 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.
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.
102 * GLib also features #GDateTime which represents a precise time.
106 * G_USEC_PER_SEC:
108 * Number of microseconds in one second (1 million).
109 * This macro is provided for code readability.
113 * GTimeVal:
114 * @tv_sec: seconds
115 * @tv_usec: microseconds
117 * Represents a precise time, with seconds and microseconds.
118 * Similar to the struct timeval returned by the gettimeofday()
119 * UNIX system call.
121 * GLib is attempting to unify around the use of 64bit integers to
122 * represent microsecond-precision time. As such, this type will be
123 * removed from a future version of GLib.
127 * GDate:
128 * @julian_days: the Julian representation of the date
129 * @julian: this bit is set if @julian_days is valid
130 * @dmy: this is set if @day, @month and @year are valid
131 * @day: the day of the day-month-year representation of the date,
132 * as a number between 1 and 31
133 * @month: the day of the day-month-year representation of the date,
134 * as a number between 1 and 12
135 * @year: the day of the day-month-year representation of the date
137 * Represents a day between January 1, Year 1 and a few thousand years in
138 * the future. None of its members should be accessed directly.
140 * If the #GDate-struct is obtained from g_date_new(), it will be safe
141 * to mutate but invalid and thus not safe for calendrical computations.
143 * If it's declared on the stack, it will contain garbage so must be
144 * initialized with g_date_clear(). g_date_clear() makes the date invalid
145 * but sane. An invalid date doesn't represent a day, it's "empty." A date
146 * becomes valid after you set it to a Julian day or you set a day, month,
147 * and year.
151 * GTime:
153 * Simply a replacement for time_t. It has been deprecated
154 * since it is not equivalent to time_t on 64-bit platforms
155 * with a 64-bit time_t. Unrelated to #GTimer.
157 * Note that #GTime is defined to always be a 32-bit integer,
158 * unlike time_t which may be 64-bit on some systems. Therefore,
159 * #GTime will overflow in the year 2038, and you cannot use the
160 * address of a #GTime variable as argument to the UNIX time()
161 * function.
163 * Instead, do the following:
164 * |[<!-- language="C" -->
165 * time_t ttime;
166 * GTime gtime;
168 * time (&ttime);
169 * gtime = (GTime)ttime;
170 * ]|
174 * GDateDMY:
175 * @G_DATE_DAY: a day
176 * @G_DATE_MONTH: a month
177 * @G_DATE_YEAR: a year
179 * This enumeration isn't used in the API, but may be useful if you need
180 * to mark a number as a day, month, or year.
184 * GDateDay:
186 * Integer representing a day of the month; between 1 and 31.
187 * #G_DATE_BAD_DAY represents an invalid day of the month.
191 * GDateMonth:
192 * @G_DATE_BAD_MONTH: invalid value
193 * @G_DATE_JANUARY: January
194 * @G_DATE_FEBRUARY: February
195 * @G_DATE_MARCH: March
196 * @G_DATE_APRIL: April
197 * @G_DATE_MAY: May
198 * @G_DATE_JUNE: June
199 * @G_DATE_JULY: July
200 * @G_DATE_AUGUST: August
201 * @G_DATE_SEPTEMBER: September
202 * @G_DATE_OCTOBER: October
203 * @G_DATE_NOVEMBER: November
204 * @G_DATE_DECEMBER: December
206 * Enumeration representing a month; values are #G_DATE_JANUARY,
207 * #G_DATE_FEBRUARY, etc. #G_DATE_BAD_MONTH is the invalid value.
211 * GDateYear:
213 * Integer representing a year; #G_DATE_BAD_YEAR is the invalid
214 * value. The year must be 1 or higher; negative (BC) years are not
215 * allowed. The year is represented with four digits.
219 * GDateWeekday:
220 * @G_DATE_BAD_WEEKDAY: invalid value
221 * @G_DATE_MONDAY: Monday
222 * @G_DATE_TUESDAY: Tuesday
223 * @G_DATE_WEDNESDAY: Wednesday
224 * @G_DATE_THURSDAY: Thursday
225 * @G_DATE_FRIDAY: Friday
226 * @G_DATE_SATURDAY: Saturday
227 * @G_DATE_SUNDAY: Sunday
229 * Enumeration representing a day of the week; #G_DATE_MONDAY,
230 * #G_DATE_TUESDAY, etc. #G_DATE_BAD_WEEKDAY is an invalid weekday.
234 * G_DATE_BAD_DAY:
236 * Represents an invalid #GDateDay.
240 * G_DATE_BAD_JULIAN:
242 * Represents an invalid Julian day number.
246 * G_DATE_BAD_YEAR:
248 * Represents an invalid year.
252 * g_date_new:
254 * Allocates a #GDate and initializes
255 * it to a sane state. The new date will
256 * be cleared (as if you'd called g_date_clear()) but invalid (it won't
257 * represent an existing day). Free the return value with g_date_free().
259 * Returns: a newly-allocated #GDate
261 GDate*
262 g_date_new (void)
264 GDate *d = g_new0 (GDate, 1); /* happily, 0 is the invalid flag for everything. */
266 return d;
270 * g_date_new_dmy:
271 * @day: day of the month
272 * @month: month of the year
273 * @year: year
275 * Like g_date_new(), but also sets the value of the date. Assuming the
276 * day-month-year triplet you pass in represents an existing day, the
277 * returned date will be valid.
279 * Returns: a newly-allocated #GDate initialized with @day, @month, and @year
281 GDate*
282 g_date_new_dmy (GDateDay day,
283 GDateMonth m,
284 GDateYear y)
286 GDate *d;
287 g_return_val_if_fail (g_date_valid_dmy (day, m, y), NULL);
289 d = g_new (GDate, 1);
291 d->julian = FALSE;
292 d->dmy = TRUE;
294 d->month = m;
295 d->day = day;
296 d->year = y;
298 g_assert (g_date_valid (d));
300 return d;
304 * g_date_new_julian:
305 * @julian_day: days since January 1, Year 1
307 * Like g_date_new(), but also sets the value of the date. Assuming the
308 * Julian day number you pass in is valid (greater than 0, less than an
309 * unreasonably large number), the returned date will be valid.
311 * Returns: a newly-allocated #GDate initialized with @julian_day
313 GDate*
314 g_date_new_julian (guint32 julian_day)
316 GDate *d;
317 g_return_val_if_fail (g_date_valid_julian (julian_day), NULL);
319 d = g_new (GDate, 1);
321 d->julian = TRUE;
322 d->dmy = FALSE;
324 d->julian_days = julian_day;
326 g_assert (g_date_valid (d));
328 return d;
332 * g_date_free:
333 * @date: a #GDate to free
335 * Frees a #GDate returned from g_date_new().
337 void
338 g_date_free (GDate *date)
340 g_return_if_fail (date != NULL);
342 g_free (date);
346 * g_date_copy:
347 * @date: a #GDate to copy
349 * Copies a GDate to a newly-allocated GDate. If the input was invalid
350 * (as determined by g_date_valid()), the invalid state will be copied
351 * as is into the new object.
353 * Returns: (transfer full): a newly-allocated #GDate initialized from @date
355 * Since: 2.56
357 GDate *
358 g_date_copy (const GDate *date)
360 GDate *res;
361 g_return_val_if_fail (date != NULL, NULL);
363 if (g_date_valid (date))
364 res = g_date_new_julian (g_date_get_julian (date));
365 else
367 res = g_date_new ();
368 *res = *date;
371 return res;
375 * g_date_valid:
376 * @date: a #GDate to check
378 * Returns %TRUE if the #GDate represents an existing day. The date must not
379 * contain garbage; it should have been initialized with g_date_clear()
380 * if it wasn't allocated by one of the g_date_new() variants.
382 * Returns: Whether the date is valid
384 gboolean
385 g_date_valid (const GDate *d)
387 g_return_val_if_fail (d != NULL, FALSE);
389 return (d->julian || d->dmy);
392 static const guint8 days_in_months[2][13] =
393 { /* error, jan feb mar apr may jun jul aug sep oct nov dec */
394 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
395 { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } /* leap year */
398 static const guint16 days_in_year[2][14] =
399 { /* 0, jan feb mar apr may jun jul aug sep oct nov dec */
400 { 0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
401 { 0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
405 * g_date_valid_month:
406 * @month: month
408 * Returns %TRUE if the month value is valid. The 12 #GDateMonth
409 * enumeration values are the only valid months.
411 * Returns: %TRUE if the month is valid
413 gboolean
414 g_date_valid_month (GDateMonth m)
416 return ( (m > G_DATE_BAD_MONTH) && (m < 13) );
420 * g_date_valid_year:
421 * @year: year
423 * Returns %TRUE if the year is valid. Any year greater than 0 is valid,
424 * though there is a 16-bit limit to what #GDate will understand.
426 * Returns: %TRUE if the year is valid
428 gboolean
429 g_date_valid_year (GDateYear y)
431 return ( y > G_DATE_BAD_YEAR );
435 * g_date_valid_day:
436 * @day: day to check
438 * Returns %TRUE if the day of the month is valid (a day is valid if it's
439 * between 1 and 31 inclusive).
441 * Returns: %TRUE if the day is valid
444 gboolean
445 g_date_valid_day (GDateDay d)
447 return ( (d > G_DATE_BAD_DAY) && (d < 32) );
451 * g_date_valid_weekday:
452 * @weekday: weekday
454 * Returns %TRUE if the weekday is valid. The seven #GDateWeekday enumeration
455 * values are the only valid weekdays.
457 * Returns: %TRUE if the weekday is valid
459 gboolean
460 g_date_valid_weekday (GDateWeekday w)
462 return ( (w > G_DATE_BAD_WEEKDAY) && (w < 8) );
466 * g_date_valid_julian:
467 * @julian_date: Julian day to check
469 * Returns %TRUE if the Julian day is valid. Anything greater than zero
470 * is basically a valid Julian, though there is a 32-bit limit.
472 * Returns: %TRUE if the Julian day is valid
474 gboolean
475 g_date_valid_julian (guint32 j)
477 return (j > G_DATE_BAD_JULIAN);
481 * g_date_valid_dmy:
482 * @day: day
483 * @month: month
484 * @year: year
486 * Returns %TRUE if the day-month-year triplet forms a valid, existing day
487 * in the range of days #GDate understands (Year 1 or later, no more than
488 * a few thousand years in the future).
490 * Returns: %TRUE if the date is a valid one
492 gboolean
493 g_date_valid_dmy (GDateDay d,
494 GDateMonth m,
495 GDateYear y)
497 /* No need to check the upper bound of @y, because #GDateYear is 16 bits wide,
498 * just like #GDate.year. */
499 return ( (m > G_DATE_BAD_MONTH) &&
500 (m < 13) &&
501 (d > G_DATE_BAD_DAY) &&
502 (y > G_DATE_BAD_YEAR) && /* must check before using g_date_is_leap_year */
503 (d <= (g_date_is_leap_year (y) ?
504 days_in_months[1][m] : days_in_months[0][m])) );
508 /* "Julian days" just means an absolute number of days, where Day 1 ==
509 * Jan 1, Year 1
511 static void
512 g_date_update_julian (const GDate *const_d)
514 GDate *d = (GDate *) const_d;
515 GDateYear year;
516 gint idx;
518 g_return_if_fail (d != NULL);
519 g_return_if_fail (d->dmy != 0);
520 g_return_if_fail (!d->julian);
521 g_return_if_fail (g_date_valid_dmy (d->day, d->month, d->year));
523 /* What we actually do is: multiply years * 365 days in the year,
524 * add the number of years divided by 4, subtract the number of
525 * years divided by 100 and add the number of years divided by 400,
526 * which accounts for leap year stuff. Code from Steffen Beyer's
527 * DateCalc.
530 year = d->year - 1; /* we know d->year > 0 since it's valid */
532 d->julian_days = year * 365U;
533 d->julian_days += (year >>= 2); /* divide by 4 and add */
534 d->julian_days -= (year /= 25); /* divides original # years by 100 */
535 d->julian_days += year >> 2; /* divides by 4, which divides original by 400 */
537 idx = g_date_is_leap_year (d->year) ? 1 : 0;
539 d->julian_days += days_in_year[idx][d->month] + d->day;
541 g_return_if_fail (g_date_valid_julian (d->julian_days));
543 d->julian = TRUE;
546 static void
547 g_date_update_dmy (const GDate *const_d)
549 GDate *d = (GDate *) const_d;
550 GDateYear y;
551 GDateMonth m;
552 GDateDay day;
554 guint32 A, B, C, D, E, M;
556 g_return_if_fail (d != NULL);
557 g_return_if_fail (d->julian);
558 g_return_if_fail (!d->dmy);
559 g_return_if_fail (g_date_valid_julian (d->julian_days));
561 /* Formula taken from the Calendar FAQ; the formula was for the
562 * Julian Period which starts on 1 January 4713 BC, so we add
563 * 1,721,425 to the number of days before doing the formula.
565 * I'm sure this can be simplified for our 1 January 1 AD period
566 * start, but I can't figure out how to unpack the formula.
569 A = d->julian_days + 1721425 + 32045;
570 B = ( 4 *(A + 36524) )/ 146097 - 1;
571 C = A - (146097 * B)/4;
572 D = ( 4 * (C + 365) ) / 1461 - 1;
573 E = C - ((1461*D) / 4);
574 M = (5 * (E - 1) + 2)/153;
576 m = M + 3 - (12*(M/10));
577 day = E - (153*M + 2)/5;
578 y = 100 * B + D - 4800 + (M/10);
580 #ifdef G_ENABLE_DEBUG
581 if (!g_date_valid_dmy (day, m, y))
582 g_warning ("OOPS julian: %u computed dmy: %u %u %u",
583 d->julian_days, day, m, y);
584 #endif
586 d->month = m;
587 d->day = day;
588 d->year = y;
590 d->dmy = TRUE;
594 * g_date_get_weekday:
595 * @date: a #GDate
597 * Returns the day of the week for a #GDate. The date must be valid.
599 * Returns: day of the week as a #GDateWeekday.
601 GDateWeekday
602 g_date_get_weekday (const GDate *d)
604 g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_WEEKDAY);
606 if (!d->julian)
607 g_date_update_julian (d);
609 g_return_val_if_fail (d->julian, G_DATE_BAD_WEEKDAY);
611 return ((d->julian_days - 1) % 7) + 1;
615 * g_date_get_month:
616 * @date: a #GDate to get the month from
618 * Returns the month of the year. The date must be valid.
620 * Returns: month of the year as a #GDateMonth
622 GDateMonth
623 g_date_get_month (const GDate *d)
625 g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_MONTH);
627 if (!d->dmy)
628 g_date_update_dmy (d);
630 g_return_val_if_fail (d->dmy, G_DATE_BAD_MONTH);
632 return d->month;
636 * g_date_get_year:
637 * @date: a #GDate
639 * Returns the year of a #GDate. The date must be valid.
641 * Returns: year in which the date falls
643 GDateYear
644 g_date_get_year (const GDate *d)
646 g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_YEAR);
648 if (!d->dmy)
649 g_date_update_dmy (d);
651 g_return_val_if_fail (d->dmy, G_DATE_BAD_YEAR);
653 return d->year;
657 * g_date_get_day:
658 * @date: a #GDate to extract the day of the month from
660 * Returns the day of the month. The date must be valid.
662 * Returns: day of the month
664 GDateDay
665 g_date_get_day (const GDate *d)
667 g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_DAY);
669 if (!d->dmy)
670 g_date_update_dmy (d);
672 g_return_val_if_fail (d->dmy, G_DATE_BAD_DAY);
674 return d->day;
678 * g_date_get_julian:
679 * @date: a #GDate to extract the Julian day from
681 * Returns the Julian day or "serial number" of the #GDate. The
682 * Julian day is simply the number of days since January 1, Year 1; i.e.,
683 * January 1, Year 1 is Julian day 1; January 2, Year 1 is Julian day 2,
684 * etc. The date must be valid.
686 * Returns: Julian day
688 guint32
689 g_date_get_julian (const GDate *d)
691 g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_JULIAN);
693 if (!d->julian)
694 g_date_update_julian (d);
696 g_return_val_if_fail (d->julian, G_DATE_BAD_JULIAN);
698 return d->julian_days;
702 * g_date_get_day_of_year:
703 * @date: a #GDate to extract day of year from
705 * Returns the day of the year, where Jan 1 is the first day of the
706 * year. The date must be valid.
708 * Returns: day of the year
710 guint
711 g_date_get_day_of_year (const GDate *d)
713 gint idx;
715 g_return_val_if_fail (g_date_valid (d), 0);
717 if (!d->dmy)
718 g_date_update_dmy (d);
720 g_return_val_if_fail (d->dmy, 0);
722 idx = g_date_is_leap_year (d->year) ? 1 : 0;
724 return (days_in_year[idx][d->month] + d->day);
728 * g_date_get_monday_week_of_year:
729 * @date: a #GDate
731 * Returns the week of the year, where weeks are understood to start on
732 * Monday. If the date is before the first Monday of the year, return 0.
733 * The date must be valid.
735 * Returns: week of the year
737 guint
738 g_date_get_monday_week_of_year (const GDate *d)
740 GDateWeekday wd;
741 guint day;
742 GDate first;
744 g_return_val_if_fail (g_date_valid (d), 0);
746 if (!d->dmy)
747 g_date_update_dmy (d);
749 g_return_val_if_fail (d->dmy, 0);
751 g_date_clear (&first, 1);
753 g_date_set_dmy (&first, 1, 1, d->year);
755 wd = g_date_get_weekday (&first) - 1; /* make Monday day 0 */
756 day = g_date_get_day_of_year (d) - 1;
758 return ((day + wd)/7U + (wd == 0 ? 1 : 0));
762 * g_date_get_sunday_week_of_year:
763 * @date: a #GDate
765 * Returns the week of the year during which this date falls, if
766 * weeks are understood to begin on Sunday. The date must be valid.
767 * Can return 0 if the day is before the first Sunday of the year.
769 * Returns: week number
771 guint
772 g_date_get_sunday_week_of_year (const GDate *d)
774 GDateWeekday wd;
775 guint day;
776 GDate first;
778 g_return_val_if_fail (g_date_valid (d), 0);
780 if (!d->dmy)
781 g_date_update_dmy (d);
783 g_return_val_if_fail (d->dmy, 0);
785 g_date_clear (&first, 1);
787 g_date_set_dmy (&first, 1, 1, d->year);
789 wd = g_date_get_weekday (&first);
790 if (wd == 7) wd = 0; /* make Sunday day 0 */
791 day = g_date_get_day_of_year (d) - 1;
793 return ((day + wd)/7U + (wd == 0 ? 1 : 0));
797 * g_date_get_iso8601_week_of_year:
798 * @date: a valid #GDate
800 * Returns the week of the year, where weeks are interpreted according
801 * to ISO 8601.
803 * Returns: ISO 8601 week number of the year.
805 * Since: 2.6
807 guint
808 g_date_get_iso8601_week_of_year (const GDate *d)
810 guint j, d4, L, d1, w;
812 g_return_val_if_fail (g_date_valid (d), 0);
814 if (!d->julian)
815 g_date_update_julian (d);
817 g_return_val_if_fail (d->julian, 0);
819 /* Formula taken from the Calendar FAQ; the formula was for the
820 * Julian Period which starts on 1 January 4713 BC, so we add
821 * 1,721,425 to the number of days before doing the formula.
823 j = d->julian_days + 1721425;
824 d4 = (j + 31741 - (j % 7)) % 146097 % 36524 % 1461;
825 L = d4 / 1460;
826 d1 = ((d4 - L) % 365) + L;
827 w = d1 / 7 + 1;
829 return w;
833 * g_date_days_between:
834 * @date1: the first date
835 * @date2: the second date
837 * Computes the number of days between two dates.
838 * If @date2 is prior to @date1, the returned value is negative.
839 * Both dates must be valid.
841 * Returns: the number of days between @date1 and @date2
843 gint
844 g_date_days_between (const GDate *d1,
845 const GDate *d2)
847 g_return_val_if_fail (g_date_valid (d1), 0);
848 g_return_val_if_fail (g_date_valid (d2), 0);
850 return (gint)g_date_get_julian (d2) - (gint)g_date_get_julian (d1);
854 * g_date_clear:
855 * @date: pointer to one or more dates to clear
856 * @n_dates: number of dates to clear
858 * Initializes one or more #GDate structs to a sane but invalid
859 * state. The cleared dates will not represent an existing date, but will
860 * not contain garbage. Useful to init a date declared on the stack.
861 * Validity can be tested with g_date_valid().
863 void
864 g_date_clear (GDate *d, guint ndates)
866 g_return_if_fail (d != NULL);
867 g_return_if_fail (ndates != 0);
869 memset (d, 0x0, ndates*sizeof (GDate));
872 G_LOCK_DEFINE_STATIC (g_date_global);
874 /* These are for the parser, output to the user should use *
875 * g_date_strftime () - this creates more never-freed memory to annoy
876 * all those memory debugger users. :-)
879 static gchar *long_month_names[13] =
881 NULL,
884 static gchar *long_month_names_alternative[13] =
886 NULL,
889 static gchar *short_month_names[13] =
891 NULL,
894 static gchar *short_month_names_alternative[13] =
896 NULL,
899 /* This tells us if we need to update the parse info */
900 static gchar *current_locale = NULL;
902 /* order of these in the current locale */
903 static GDateDMY dmy_order[3] =
905 G_DATE_DAY, G_DATE_MONTH, G_DATE_YEAR
908 /* Where to chop two-digit years: i.e., for the 1930 default, numbers
909 * 29 and below are counted as in the year 2000, numbers 30 and above
910 * are counted as in the year 1900.
913 static const GDateYear twodigit_start_year = 1930;
915 /* It is impossible to enter a year between 1 AD and 99 AD with this
916 * in effect.
918 static gboolean using_twodigit_years = FALSE;
920 /* Adjustment of locale era to AD, non-zero means using locale era
922 static gint locale_era_adjust = 0;
924 struct _GDateParseTokens {
925 gint num_ints;
926 gint n[3];
927 guint month;
930 typedef struct _GDateParseTokens GDateParseTokens;
932 #define NUM_LEN 10
934 /* HOLDS: g_date_global_lock */
935 static void
936 g_date_fill_parse_tokens (const gchar *str, GDateParseTokens *pt)
938 gchar num[4][NUM_LEN+1];
939 gint i;
940 const guchar *s;
942 /* We count 4, but store 3; so we can give an error
943 * if there are 4.
945 num[0][0] = num[1][0] = num[2][0] = num[3][0] = '\0';
947 s = (const guchar *) str;
948 pt->num_ints = 0;
949 while (*s && pt->num_ints < 4)
952 i = 0;
953 while (*s && g_ascii_isdigit (*s) && i < NUM_LEN)
955 num[pt->num_ints][i] = *s;
956 ++s;
957 ++i;
960 if (i > 0)
962 num[pt->num_ints][i] = '\0';
963 ++(pt->num_ints);
966 if (*s == '\0') break;
968 ++s;
971 pt->n[0] = pt->num_ints > 0 ? atoi (num[0]) : 0;
972 pt->n[1] = pt->num_ints > 1 ? atoi (num[1]) : 0;
973 pt->n[2] = pt->num_ints > 2 ? atoi (num[2]) : 0;
975 pt->month = G_DATE_BAD_MONTH;
977 if (pt->num_ints < 3)
979 gchar *casefold;
980 gchar *normalized;
982 casefold = g_utf8_casefold (str, -1);
983 normalized = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
984 g_free (casefold);
986 i = 1;
987 while (i < 13)
989 /* Here month names may be in a genitive case if the language
990 * grammatical rules require it.
991 * Examples of how January may look in some languages:
992 * Catalan: "de gener", Croatian: "siječnja", Polish: "stycznia",
993 * Upper Sorbian: "januara".
994 * Note that most of the languages can't or don't use the the
995 * genitive case here so they use nominative everywhere.
996 * For example, English always uses "January".
998 if (long_month_names[i] != NULL)
1000 const gchar *found = strstr (normalized, long_month_names[i]);
1002 if (found != NULL)
1004 pt->month = i;
1005 break;
1009 /* Here month names will be in a nominative case.
1010 * Examples of how January may look in some languages:
1011 * Catalan: "gener", Croatian: "Siječanj", Polish: "styczeń",
1012 * Upper Sorbian: "Januar".
1014 if (long_month_names_alternative[i] != NULL)
1016 const gchar *found = strstr (normalized, long_month_names_alternative[i]);
1018 if (found != NULL)
1020 pt->month = i;
1021 break;
1025 /* Differences between abbreviated nominative and abbreviated
1026 * genitive month names are visible in very few languages but
1027 * let's handle them.
1029 if (short_month_names[i] != NULL)
1031 const gchar *found = strstr (normalized, short_month_names[i]);
1033 if (found != NULL)
1035 pt->month = i;
1036 break;
1040 if (short_month_names_alternative[i] != NULL)
1042 const gchar *found = strstr (normalized, short_month_names_alternative[i]);
1044 if (found != NULL)
1046 pt->month = i;
1047 break;
1051 ++i;
1054 g_free (normalized);
1058 /* HOLDS: g_date_global_lock */
1059 static void
1060 g_date_prepare_to_parse (const gchar *str,
1061 GDateParseTokens *pt)
1063 const gchar *locale = setlocale (LC_TIME, NULL);
1064 gboolean recompute_localeinfo = FALSE;
1065 GDate d;
1067 g_return_if_fail (locale != NULL); /* should not happen */
1069 g_date_clear (&d, 1); /* clear for scratch use */
1071 if ( (current_locale == NULL) || (strcmp (locale, current_locale) != 0) )
1072 recompute_localeinfo = TRUE; /* Uh, there used to be a reason for the temporary */
1074 if (recompute_localeinfo)
1076 int i = 1;
1077 GDateParseTokens testpt;
1078 gchar buf[128];
1080 g_free (current_locale); /* still works if current_locale == NULL */
1082 current_locale = g_strdup (locale);
1084 short_month_names[0] = "Error";
1085 long_month_names[0] = "Error";
1087 while (i < 13)
1089 gchar *casefold;
1091 g_date_set_dmy (&d, 1, i, 1976);
1093 g_return_if_fail (g_date_valid (&d));
1095 g_date_strftime (buf, 127, "%b", &d);
1097 casefold = g_utf8_casefold (buf, -1);
1098 g_free (short_month_names[i]);
1099 short_month_names[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
1100 g_free (casefold);
1102 g_date_strftime (buf, 127, "%B", &d);
1103 casefold = g_utf8_casefold (buf, -1);
1104 g_free (long_month_names[i]);
1105 long_month_names[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
1106 g_free (casefold);
1108 g_date_strftime (buf, 127, "%Ob", &d);
1109 casefold = g_utf8_casefold (buf, -1);
1110 g_free (short_month_names_alternative[i]);
1111 short_month_names_alternative[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
1112 g_free (casefold);
1114 g_date_strftime (buf, 127, "%OB", &d);
1115 casefold = g_utf8_casefold (buf, -1);
1116 g_free (long_month_names_alternative[i]);
1117 long_month_names_alternative[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
1118 g_free (casefold);
1120 ++i;
1123 /* Determine DMY order */
1125 /* had to pick a random day - don't change this, some strftimes
1126 * are broken on some days, and this one is good so far. */
1127 g_date_set_dmy (&d, 4, 7, 1976);
1129 g_date_strftime (buf, 127, "%x", &d);
1131 g_date_fill_parse_tokens (buf, &testpt);
1133 i = 0;
1134 while (i < testpt.num_ints)
1136 switch (testpt.n[i])
1138 case 7:
1139 dmy_order[i] = G_DATE_MONTH;
1140 break;
1141 case 4:
1142 dmy_order[i] = G_DATE_DAY;
1143 break;
1144 case 76:
1145 using_twodigit_years = TRUE; /* FALL THRU */
1146 case 1976:
1147 dmy_order[i] = G_DATE_YEAR;
1148 break;
1149 default:
1150 /* assume locale era */
1151 locale_era_adjust = 1976 - testpt.n[i];
1152 dmy_order[i] = G_DATE_YEAR;
1153 break;
1155 ++i;
1158 #if defined(G_ENABLE_DEBUG) && 0
1159 DEBUG_MSG (("**GDate prepared a new set of locale-specific parse rules."));
1160 i = 1;
1161 while (i < 13)
1163 DEBUG_MSG ((" %s %s", long_month_names[i], short_month_names[i]));
1164 ++i;
1166 DEBUG_MSG (("Alternative month names:"));
1167 i = 1;
1168 while (i < 13)
1170 DEBUG_MSG ((" %s %s", long_month_names_alternative[i], short_month_names_alternative[i]));
1171 ++i;
1173 if (using_twodigit_years)
1175 DEBUG_MSG (("**Using twodigit years with cutoff year: %u", twodigit_start_year));
1178 gchar *strings[3];
1179 i = 0;
1180 while (i < 3)
1182 switch (dmy_order[i])
1184 case G_DATE_MONTH:
1185 strings[i] = "Month";
1186 break;
1187 case G_DATE_YEAR:
1188 strings[i] = "Year";
1189 break;
1190 case G_DATE_DAY:
1191 strings[i] = "Day";
1192 break;
1193 default:
1194 strings[i] = NULL;
1195 break;
1197 ++i;
1199 DEBUG_MSG (("**Order: %s, %s, %s", strings[0], strings[1], strings[2]));
1200 DEBUG_MSG (("**Sample date in this locale: '%s'", buf));
1202 #endif
1205 g_date_fill_parse_tokens (str, pt);
1209 * g_date_set_parse:
1210 * @date: a #GDate to fill in
1211 * @str: string to parse
1213 * Parses a user-inputted string @str, and try to figure out what date it
1214 * represents, taking the [current locale][setlocale] into account. If the
1215 * string is successfully parsed, the date will be valid after the call.
1216 * Otherwise, it will be invalid. You should check using g_date_valid()
1217 * to see whether the parsing succeeded.
1219 * This function is not appropriate for file formats and the like; it
1220 * isn't very precise, and its exact behavior varies with the locale.
1221 * It's intended to be a heuristic routine that guesses what the user
1222 * means by a given string (and it does work pretty well in that
1223 * capacity).
1225 void
1226 g_date_set_parse (GDate *d,
1227 const gchar *str)
1229 GDateParseTokens pt;
1230 guint m = G_DATE_BAD_MONTH, day = G_DATE_BAD_DAY, y = G_DATE_BAD_YEAR;
1232 g_return_if_fail (d != NULL);
1234 /* set invalid */
1235 g_date_clear (d, 1);
1237 G_LOCK (g_date_global);
1239 g_date_prepare_to_parse (str, &pt);
1241 DEBUG_MSG (("Found %d ints, '%d' '%d' '%d' and written out month %d",
1242 pt.num_ints, pt.n[0], pt.n[1], pt.n[2], pt.month));
1245 if (pt.num_ints == 4)
1247 G_UNLOCK (g_date_global);
1248 return; /* presumably a typo; bail out. */
1251 if (pt.num_ints > 1)
1253 int i = 0;
1254 int j = 0;
1256 g_assert (pt.num_ints < 4); /* i.e., it is 2 or 3 */
1258 while (i < pt.num_ints && j < 3)
1260 switch (dmy_order[j])
1262 case G_DATE_MONTH:
1264 if (pt.num_ints == 2 && pt.month != G_DATE_BAD_MONTH)
1266 m = pt.month;
1267 ++j; /* skip months, but don't skip this number */
1268 continue;
1270 else
1271 m = pt.n[i];
1273 break;
1274 case G_DATE_DAY:
1276 if (pt.num_ints == 2 && pt.month == G_DATE_BAD_MONTH)
1278 day = 1;
1279 ++j; /* skip days, since we may have month/year */
1280 continue;
1282 day = pt.n[i];
1284 break;
1285 case G_DATE_YEAR:
1287 y = pt.n[i];
1289 if (locale_era_adjust != 0)
1291 y += locale_era_adjust;
1293 else if (using_twodigit_years && y < 100)
1295 guint two = twodigit_start_year % 100;
1296 guint century = (twodigit_start_year / 100) * 100;
1298 if (y < two)
1299 century += 100;
1301 y += century;
1304 break;
1305 default:
1306 break;
1309 ++i;
1310 ++j;
1314 if (pt.num_ints == 3 && !g_date_valid_dmy (day, m, y))
1316 /* Try YYYY MM DD */
1317 y = pt.n[0];
1318 m = pt.n[1];
1319 day = pt.n[2];
1321 if (using_twodigit_years && y < 100)
1322 y = G_DATE_BAD_YEAR; /* avoids ambiguity */
1324 else if (pt.num_ints == 2)
1326 if (m == G_DATE_BAD_MONTH && pt.month != G_DATE_BAD_MONTH)
1327 m = pt.month;
1330 else if (pt.num_ints == 1)
1332 if (pt.month != G_DATE_BAD_MONTH)
1334 /* Month name and year? */
1335 m = pt.month;
1336 day = 1;
1337 y = pt.n[0];
1339 else
1341 /* Try yyyymmdd and yymmdd */
1343 m = (pt.n[0]/100) % 100;
1344 day = pt.n[0] % 100;
1345 y = pt.n[0]/10000;
1347 /* FIXME move this into a separate function */
1348 if (using_twodigit_years && y < 100)
1350 guint two = twodigit_start_year % 100;
1351 guint century = (twodigit_start_year / 100) * 100;
1353 if (y < two)
1354 century += 100;
1356 y += century;
1361 /* See if we got anything valid out of all this. */
1362 /* y < 8000 is to catch 19998 style typos; the library is OK up to 65535 or so */
1363 if (y < 8000 && g_date_valid_dmy (day, m, y))
1365 d->month = m;
1366 d->day = day;
1367 d->year = y;
1368 d->dmy = TRUE;
1370 #ifdef G_ENABLE_DEBUG
1371 else
1373 DEBUG_MSG (("Rejected DMY %u %u %u", day, m, y));
1375 #endif
1376 G_UNLOCK (g_date_global);
1380 * g_date_set_time_t:
1381 * @date: a #GDate
1382 * @timet: time_t value to set
1384 * Sets the value of a date to the date corresponding to a time
1385 * specified as a time_t. The time to date conversion is done using
1386 * the user's current timezone.
1388 * To set the value of a date to the current day, you could write:
1389 * |[<!-- language="C" -->
1390 * time_t now = time (NULL);
1391 * if (now == (time_t) -1)
1392 * // handle the error
1393 * g_date_set_time_t (date, now);
1394 * ]|
1396 * Since: 2.10
1398 void
1399 g_date_set_time_t (GDate *date,
1400 time_t timet)
1402 struct tm tm;
1404 g_return_if_fail (date != NULL);
1406 #ifdef HAVE_LOCALTIME_R
1407 localtime_r (&timet, &tm);
1408 #else
1410 struct tm *ptm = localtime (&timet);
1412 if (ptm == NULL)
1414 /* Happens at least in Microsoft's C library if you pass a
1415 * negative time_t. Use 2000-01-01 as default date.
1417 #ifndef G_DISABLE_CHECKS
1418 g_return_if_fail_warning (G_LOG_DOMAIN, "g_date_set_time", "ptm != NULL");
1419 #endif
1421 tm.tm_mon = 0;
1422 tm.tm_mday = 1;
1423 tm.tm_year = 100;
1425 else
1426 memcpy ((void *) &tm, (void *) ptm, sizeof(struct tm));
1428 #endif
1430 date->julian = FALSE;
1432 date->month = tm.tm_mon + 1;
1433 date->day = tm.tm_mday;
1434 date->year = tm.tm_year + 1900;
1436 g_return_if_fail (g_date_valid_dmy (date->day, date->month, date->year));
1438 date->dmy = TRUE;
1443 * g_date_set_time:
1444 * @date: a #GDate.
1445 * @time_: #GTime value to set.
1447 * Sets the value of a date from a #GTime value.
1448 * The time to date conversion is done using the user's current timezone.
1450 * Deprecated: 2.10: Use g_date_set_time_t() instead.
1452 void
1453 g_date_set_time (GDate *date,
1454 GTime time_)
1456 g_date_set_time_t (date, (time_t) time_);
1460 * g_date_set_time_val:
1461 * @date: a #GDate
1462 * @timeval: #GTimeVal value to set
1464 * Sets the value of a date from a #GTimeVal value. Note that the
1465 * @tv_usec member is ignored, because #GDate can't make use of the
1466 * additional precision.
1468 * The time to date conversion is done using the user's current timezone.
1470 * Since: 2.10
1472 void
1473 g_date_set_time_val (GDate *date,
1474 GTimeVal *timeval)
1476 g_date_set_time_t (date, (time_t) timeval->tv_sec);
1480 * g_date_set_month:
1481 * @date: a #GDate
1482 * @month: month to set
1484 * Sets the month of the year for a #GDate. If the resulting
1485 * day-month-year triplet is invalid, the date will be invalid.
1487 void
1488 g_date_set_month (GDate *d,
1489 GDateMonth m)
1491 g_return_if_fail (d != NULL);
1492 g_return_if_fail (g_date_valid_month (m));
1494 if (d->julian && !d->dmy) g_date_update_dmy(d);
1495 d->julian = FALSE;
1497 d->month = m;
1499 if (g_date_valid_dmy (d->day, d->month, d->year))
1500 d->dmy = TRUE;
1501 else
1502 d->dmy = FALSE;
1506 * g_date_set_day:
1507 * @date: a #GDate
1508 * @day: day to set
1510 * Sets the day of the month for a #GDate. If the resulting
1511 * day-month-year triplet is invalid, the date will be invalid.
1513 void
1514 g_date_set_day (GDate *d,
1515 GDateDay day)
1517 g_return_if_fail (d != NULL);
1518 g_return_if_fail (g_date_valid_day (day));
1520 if (d->julian && !d->dmy) g_date_update_dmy(d);
1521 d->julian = FALSE;
1523 d->day = day;
1525 if (g_date_valid_dmy (d->day, d->month, d->year))
1526 d->dmy = TRUE;
1527 else
1528 d->dmy = FALSE;
1532 * g_date_set_year:
1533 * @date: a #GDate
1534 * @year: year to set
1536 * Sets the year for a #GDate. If the resulting day-month-year
1537 * triplet is invalid, the date will be invalid.
1539 void
1540 g_date_set_year (GDate *d,
1541 GDateYear y)
1543 g_return_if_fail (d != NULL);
1544 g_return_if_fail (g_date_valid_year (y));
1546 if (d->julian && !d->dmy) g_date_update_dmy(d);
1547 d->julian = FALSE;
1549 d->year = y;
1551 if (g_date_valid_dmy (d->day, d->month, d->year))
1552 d->dmy = TRUE;
1553 else
1554 d->dmy = FALSE;
1558 * g_date_set_dmy:
1559 * @date: a #GDate
1560 * @day: day
1561 * @month: month
1562 * @y: year
1564 * Sets the value of a #GDate from a day, month, and year.
1565 * The day-month-year triplet must be valid; if you aren't
1566 * sure it is, call g_date_valid_dmy() to check before you
1567 * set it.
1569 void
1570 g_date_set_dmy (GDate *d,
1571 GDateDay day,
1572 GDateMonth m,
1573 GDateYear y)
1575 g_return_if_fail (d != NULL);
1576 g_return_if_fail (g_date_valid_dmy (day, m, y));
1578 d->julian = FALSE;
1580 d->month = m;
1581 d->day = day;
1582 d->year = y;
1584 d->dmy = TRUE;
1588 * g_date_set_julian:
1589 * @date: a #GDate
1590 * @julian_date: Julian day number (days since January 1, Year 1)
1592 * Sets the value of a #GDate from a Julian day number.
1594 void
1595 g_date_set_julian (GDate *d,
1596 guint32 j)
1598 g_return_if_fail (d != NULL);
1599 g_return_if_fail (g_date_valid_julian (j));
1601 d->julian_days = j;
1602 d->julian = TRUE;
1603 d->dmy = FALSE;
1607 * g_date_is_first_of_month:
1608 * @date: a #GDate to check
1610 * Returns %TRUE if the date is on the first of a month.
1611 * The date must be valid.
1613 * Returns: %TRUE if the date is the first of the month
1615 gboolean
1616 g_date_is_first_of_month (const GDate *d)
1618 g_return_val_if_fail (g_date_valid (d), FALSE);
1620 if (!d->dmy)
1621 g_date_update_dmy (d);
1623 g_return_val_if_fail (d->dmy, FALSE);
1625 if (d->day == 1) return TRUE;
1626 else return FALSE;
1630 * g_date_is_last_of_month:
1631 * @date: a #GDate to check
1633 * Returns %TRUE if the date is the last day of the month.
1634 * The date must be valid.
1636 * Returns: %TRUE if the date is the last day of the month
1638 gboolean
1639 g_date_is_last_of_month (const GDate *d)
1641 gint idx;
1643 g_return_val_if_fail (g_date_valid (d), FALSE);
1645 if (!d->dmy)
1646 g_date_update_dmy (d);
1648 g_return_val_if_fail (d->dmy, FALSE);
1650 idx = g_date_is_leap_year (d->year) ? 1 : 0;
1652 if (d->day == days_in_months[idx][d->month]) return TRUE;
1653 else return FALSE;
1657 * g_date_add_days:
1658 * @date: a #GDate to increment
1659 * @n_days: number of days to move the date forward
1661 * Increments a date some number of days.
1662 * To move forward by weeks, add weeks*7 days.
1663 * The date must be valid.
1665 void
1666 g_date_add_days (GDate *d,
1667 guint ndays)
1669 g_return_if_fail (g_date_valid (d));
1671 if (!d->julian)
1672 g_date_update_julian (d);
1674 g_return_if_fail (d->julian);
1675 g_return_if_fail (ndays <= G_MAXUINT32 - d->julian_days);
1677 d->julian_days += ndays;
1678 d->dmy = FALSE;
1682 * g_date_subtract_days:
1683 * @date: a #GDate to decrement
1684 * @n_days: number of days to move
1686 * Moves a date some number of days into the past.
1687 * To move by weeks, just move by weeks*7 days.
1688 * The date must be valid.
1690 void
1691 g_date_subtract_days (GDate *d,
1692 guint ndays)
1694 g_return_if_fail (g_date_valid (d));
1696 if (!d->julian)
1697 g_date_update_julian (d);
1699 g_return_if_fail (d->julian);
1700 g_return_if_fail (d->julian_days > ndays);
1702 d->julian_days -= ndays;
1703 d->dmy = FALSE;
1707 * g_date_add_months:
1708 * @date: a #GDate to increment
1709 * @n_months: number of months to move forward
1711 * Increments a date by some number of months.
1712 * If the day of the month is greater than 28,
1713 * this routine may change the day of the month
1714 * (because the destination month may not have
1715 * the current day in it). The date must be valid.
1717 void
1718 g_date_add_months (GDate *d,
1719 guint nmonths)
1721 guint years, months;
1722 gint idx;
1724 g_return_if_fail (g_date_valid (d));
1726 if (!d->dmy)
1727 g_date_update_dmy (d);
1729 g_return_if_fail (d->dmy != 0);
1730 g_return_if_fail (nmonths <= G_MAXUINT - (d->month - 1));
1732 nmonths += d->month - 1;
1734 years = nmonths/12;
1735 months = nmonths%12;
1737 g_return_if_fail (years <= G_MAXUINT16 - d->year);
1739 d->month = months + 1;
1740 d->year += years;
1742 idx = g_date_is_leap_year (d->year) ? 1 : 0;
1744 if (d->day > days_in_months[idx][d->month])
1745 d->day = days_in_months[idx][d->month];
1747 d->julian = FALSE;
1749 g_return_if_fail (g_date_valid (d));
1753 * g_date_subtract_months:
1754 * @date: a #GDate to decrement
1755 * @n_months: number of months to move
1757 * Moves a date some number of months into the past.
1758 * If the current day of the month doesn't exist in
1759 * the destination month, the day of the month
1760 * may change. The date must be valid.
1762 void
1763 g_date_subtract_months (GDate *d,
1764 guint nmonths)
1766 guint years, months;
1767 gint idx;
1769 g_return_if_fail (g_date_valid (d));
1771 if (!d->dmy)
1772 g_date_update_dmy (d);
1774 g_return_if_fail (d->dmy != 0);
1776 years = nmonths/12;
1777 months = nmonths%12;
1779 g_return_if_fail (d->year > years);
1781 d->year -= years;
1783 if (d->month > months) d->month -= months;
1784 else
1786 months -= d->month;
1787 d->month = 12 - months;
1788 d->year -= 1;
1791 idx = g_date_is_leap_year (d->year) ? 1 : 0;
1793 if (d->day > days_in_months[idx][d->month])
1794 d->day = days_in_months[idx][d->month];
1796 d->julian = FALSE;
1798 g_return_if_fail (g_date_valid (d));
1802 * g_date_add_years:
1803 * @date: a #GDate to increment
1804 * @n_years: number of years to move forward
1806 * Increments a date by some number of years.
1807 * If the date is February 29, and the destination
1808 * year is not a leap year, the date will be changed
1809 * to February 28. The date must be valid.
1811 void
1812 g_date_add_years (GDate *d,
1813 guint nyears)
1815 g_return_if_fail (g_date_valid (d));
1817 if (!d->dmy)
1818 g_date_update_dmy (d);
1820 g_return_if_fail (d->dmy != 0);
1821 g_return_if_fail (nyears <= G_MAXUINT16 - d->year);
1823 d->year += nyears;
1825 if (d->month == 2 && d->day == 29)
1827 if (!g_date_is_leap_year (d->year))
1828 d->day = 28;
1831 d->julian = FALSE;
1835 * g_date_subtract_years:
1836 * @date: a #GDate to decrement
1837 * @n_years: number of years to move
1839 * Moves a date some number of years into the past.
1840 * If the current day doesn't exist in the destination
1841 * year (i.e. it's February 29 and you move to a non-leap-year)
1842 * then the day is changed to February 29. The date
1843 * must be valid.
1845 void
1846 g_date_subtract_years (GDate *d,
1847 guint nyears)
1849 g_return_if_fail (g_date_valid (d));
1851 if (!d->dmy)
1852 g_date_update_dmy (d);
1854 g_return_if_fail (d->dmy != 0);
1855 g_return_if_fail (d->year > nyears);
1857 d->year -= nyears;
1859 if (d->month == 2 && d->day == 29)
1861 if (!g_date_is_leap_year (d->year))
1862 d->day = 28;
1865 d->julian = FALSE;
1869 * g_date_is_leap_year:
1870 * @year: year to check
1872 * Returns %TRUE if the year is a leap year.
1874 * For the purposes of this function, leap year is every year
1875 * divisible by 4 unless that year is divisible by 100. If it
1876 * is divisible by 100 it would be a leap year only if that year
1877 * is also divisible by 400.
1879 * Returns: %TRUE if the year is a leap year
1881 gboolean
1882 g_date_is_leap_year (GDateYear year)
1884 g_return_val_if_fail (g_date_valid_year (year), FALSE);
1886 return ( (((year % 4) == 0) && ((year % 100) != 0)) ||
1887 (year % 400) == 0 );
1891 * g_date_get_days_in_month:
1892 * @month: month
1893 * @year: year
1895 * Returns the number of days in a month, taking leap
1896 * years into account.
1898 * Returns: number of days in @month during the @year
1900 guint8
1901 g_date_get_days_in_month (GDateMonth month,
1902 GDateYear year)
1904 gint idx;
1906 g_return_val_if_fail (g_date_valid_year (year), 0);
1907 g_return_val_if_fail (g_date_valid_month (month), 0);
1909 idx = g_date_is_leap_year (year) ? 1 : 0;
1911 return days_in_months[idx][month];
1915 * g_date_get_monday_weeks_in_year:
1916 * @year: a year
1918 * Returns the number of weeks in the year, where weeks
1919 * are taken to start on Monday. Will be 52 or 53. The
1920 * date must be valid. (Years always have 52 7-day periods,
1921 * plus 1 or 2 extra days depending on whether it's a leap
1922 * year. This function is basically telling you how many
1923 * Mondays are in the year, i.e. there are 53 Mondays if
1924 * one of the extra days happens to be a Monday.)
1926 * Returns: number of Mondays in the year
1928 guint8
1929 g_date_get_monday_weeks_in_year (GDateYear year)
1931 GDate d;
1933 g_return_val_if_fail (g_date_valid_year (year), 0);
1935 g_date_clear (&d, 1);
1936 g_date_set_dmy (&d, 1, 1, year);
1937 if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1938 g_date_set_dmy (&d, 31, 12, year);
1939 if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1940 if (g_date_is_leap_year (year))
1942 g_date_set_dmy (&d, 2, 1, year);
1943 if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1944 g_date_set_dmy (&d, 30, 12, year);
1945 if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1947 return 52;
1951 * g_date_get_sunday_weeks_in_year:
1952 * @year: year to count weeks in
1954 * Returns the number of weeks in the year, where weeks
1955 * are taken to start on Sunday. Will be 52 or 53. The
1956 * date must be valid. (Years always have 52 7-day periods,
1957 * plus 1 or 2 extra days depending on whether it's a leap
1958 * year. This function is basically telling you how many
1959 * Sundays are in the year, i.e. there are 53 Sundays if
1960 * one of the extra days happens to be a Sunday.)
1962 * Returns: the number of weeks in @year
1964 guint8
1965 g_date_get_sunday_weeks_in_year (GDateYear year)
1967 GDate d;
1969 g_return_val_if_fail (g_date_valid_year (year), 0);
1971 g_date_clear (&d, 1);
1972 g_date_set_dmy (&d, 1, 1, year);
1973 if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1974 g_date_set_dmy (&d, 31, 12, year);
1975 if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1976 if (g_date_is_leap_year (year))
1978 g_date_set_dmy (&d, 2, 1, year);
1979 if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1980 g_date_set_dmy (&d, 30, 12, year);
1981 if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1983 return 52;
1987 * g_date_compare:
1988 * @lhs: first date to compare
1989 * @rhs: second date to compare
1991 * qsort()-style comparison function for dates.
1992 * Both dates must be valid.
1994 * Returns: 0 for equal, less than zero if @lhs is less than @rhs,
1995 * greater than zero if @lhs is greater than @rhs
1997 gint
1998 g_date_compare (const GDate *lhs,
1999 const GDate *rhs)
2001 g_return_val_if_fail (lhs != NULL, 0);
2002 g_return_val_if_fail (rhs != NULL, 0);
2003 g_return_val_if_fail (g_date_valid (lhs), 0);
2004 g_return_val_if_fail (g_date_valid (rhs), 0);
2006 /* Remember the self-comparison case! I think it works right now. */
2008 while (TRUE)
2010 if (lhs->julian && rhs->julian)
2012 if (lhs->julian_days < rhs->julian_days) return -1;
2013 else if (lhs->julian_days > rhs->julian_days) return 1;
2014 else return 0;
2016 else if (lhs->dmy && rhs->dmy)
2018 if (lhs->year < rhs->year) return -1;
2019 else if (lhs->year > rhs->year) return 1;
2020 else
2022 if (lhs->month < rhs->month) return -1;
2023 else if (lhs->month > rhs->month) return 1;
2024 else
2026 if (lhs->day < rhs->day) return -1;
2027 else if (lhs->day > rhs->day) return 1;
2028 else return 0;
2034 else
2036 if (!lhs->julian) g_date_update_julian (lhs);
2037 if (!rhs->julian) g_date_update_julian (rhs);
2038 g_return_val_if_fail (lhs->julian, 0);
2039 g_return_val_if_fail (rhs->julian, 0);
2043 return 0; /* warnings */
2047 * g_date_to_struct_tm:
2048 * @date: a #GDate to set the struct tm from
2049 * @tm: (not nullable): struct tm to fill
2051 * Fills in the date-related bits of a struct tm using the @date value.
2052 * Initializes the non-date parts with something sane but meaningless.
2054 void
2055 g_date_to_struct_tm (const GDate *d,
2056 struct tm *tm)
2058 GDateWeekday day;
2060 g_return_if_fail (g_date_valid (d));
2061 g_return_if_fail (tm != NULL);
2063 if (!d->dmy)
2064 g_date_update_dmy (d);
2066 g_return_if_fail (d->dmy != 0);
2068 /* zero all the irrelevant fields to be sure they're valid */
2070 /* On Linux and maybe other systems, there are weird non-POSIX
2071 * fields on the end of struct tm that choke strftime if they
2072 * contain garbage. So we need to 0 the entire struct, not just the
2073 * fields we know to exist.
2076 memset (tm, 0x0, sizeof (struct tm));
2078 tm->tm_mday = d->day;
2079 tm->tm_mon = d->month - 1; /* 0-11 goes in tm */
2080 tm->tm_year = ((int)d->year) - 1900; /* X/Open says tm_year can be negative */
2082 day = g_date_get_weekday (d);
2083 if (day == 7) day = 0; /* struct tm wants days since Sunday, so Sunday is 0 */
2085 tm->tm_wday = (int)day;
2087 tm->tm_yday = g_date_get_day_of_year (d) - 1; /* 0 to 365 */
2088 tm->tm_isdst = -1; /* -1 means "information not available" */
2092 * g_date_clamp:
2093 * @date: a #GDate to clamp
2094 * @min_date: minimum accepted value for @date
2095 * @max_date: maximum accepted value for @date
2097 * If @date is prior to @min_date, sets @date equal to @min_date.
2098 * If @date falls after @max_date, sets @date equal to @max_date.
2099 * Otherwise, @date is unchanged.
2100 * Either of @min_date and @max_date may be %NULL.
2101 * All non-%NULL dates must be valid.
2103 void
2104 g_date_clamp (GDate *date,
2105 const GDate *min_date,
2106 const GDate *max_date)
2108 g_return_if_fail (g_date_valid (date));
2110 if (min_date != NULL)
2111 g_return_if_fail (g_date_valid (min_date));
2113 if (max_date != NULL)
2114 g_return_if_fail (g_date_valid (max_date));
2116 if (min_date != NULL && max_date != NULL)
2117 g_return_if_fail (g_date_compare (min_date, max_date) <= 0);
2119 if (min_date && g_date_compare (date, min_date) < 0)
2120 *date = *min_date;
2122 if (max_date && g_date_compare (max_date, date) < 0)
2123 *date = *max_date;
2127 * g_date_order:
2128 * @date1: the first date
2129 * @date2: the second date
2131 * Checks if @date1 is less than or equal to @date2,
2132 * and swap the values if this is not the case.
2134 void
2135 g_date_order (GDate *date1,
2136 GDate *date2)
2138 g_return_if_fail (g_date_valid (date1));
2139 g_return_if_fail (g_date_valid (date2));
2141 if (g_date_compare (date1, date2) > 0)
2143 GDate tmp = *date1;
2144 *date1 = *date2;
2145 *date2 = tmp;
2149 #ifdef G_OS_WIN32
2150 static void
2151 append_month_name (GArray *result,
2152 LCID lcid,
2153 SYSTEMTIME *systemtime,
2154 gboolean abbreviated,
2155 gboolean alternative)
2157 int n;
2158 WORD base;
2159 LPCWSTR lpFormat;
2161 if (alternative)
2163 base = abbreviated ? LOCALE_SABBREVMONTHNAME1 : LOCALE_SMONTHNAME1;
2164 n = GetLocaleInfoW (lcid, base + systemtime->wMonth - 1, NULL, 0);
2165 g_array_set_size (result, result->len + n);
2166 GetLocaleInfoW (lcid, base + systemtime->wMonth - 1,
2167 ((wchar_t *) result->data) + result->len - n, n);
2168 g_array_set_size (result, result->len - 1);
2170 else
2172 /* According to MSDN, this is the correct method to obtain
2173 * the form of the month name used when formatting a full
2174 * date; it must be a genitive case in some languages.
2176 lpFormat = abbreviated ? L"ddMMM" : L"ddMMMM";
2177 n = GetDateFormatW (lcid, 0, systemtime, lpFormat, NULL, 0);
2178 g_array_set_size (result, result->len + n);
2179 GetDateFormatW (lcid, 0, systemtime, lpFormat,
2180 ((wchar_t *) result->data) + result->len - n, n);
2181 /* We have obtained a day number as two digits and the month name.
2182 * Now let's get rid of those two digits: overwrite them with the
2183 * month name.
2185 memmove (((wchar_t *) result->data) + result->len - n,
2186 ((wchar_t *) result->data) + result->len - n + 2,
2187 (n - 2) * sizeof (wchar_t));
2188 g_array_set_size (result, result->len - 3);
2192 static gsize
2193 win32_strftime_helper (const GDate *d,
2194 const gchar *format,
2195 const struct tm *tm,
2196 gchar *s,
2197 gsize slen)
2199 SYSTEMTIME systemtime;
2200 TIME_ZONE_INFORMATION tzinfo;
2201 LCID lcid;
2202 int n, k;
2203 GArray *result;
2204 const gchar *p;
2205 gunichar c, modifier;
2206 const wchar_t digits[] = L"0123456789";
2207 gchar *convbuf;
2208 glong convlen = 0;
2209 gsize retval;
2211 systemtime.wYear = tm->tm_year + 1900;
2212 systemtime.wMonth = tm->tm_mon + 1;
2213 systemtime.wDayOfWeek = tm->tm_wday;
2214 systemtime.wDay = tm->tm_mday;
2215 systemtime.wHour = tm->tm_hour;
2216 systemtime.wMinute = tm->tm_min;
2217 systemtime.wSecond = tm->tm_sec;
2218 systemtime.wMilliseconds = 0;
2220 lcid = GetThreadLocale ();
2221 result = g_array_sized_new (FALSE, FALSE, sizeof (wchar_t), MAX (128, strlen (format) * 2));
2223 p = format;
2224 while (*p)
2226 c = g_utf8_get_char (p);
2227 if (c == '%')
2229 p = g_utf8_next_char (p);
2230 if (!*p)
2232 s[0] = '\0';
2233 g_array_free (result, TRUE);
2235 return 0;
2238 modifier = '\0';
2239 c = g_utf8_get_char (p);
2240 if (c == 'E' || c == 'O')
2242 /* "%OB", "%Ob", and "%Oh" are supported, ignore other modified
2243 * conversion specifiers for now.
2245 modifier = c;
2246 p = g_utf8_next_char (p);
2247 if (!*p)
2249 s[0] = '\0';
2250 g_array_free (result, TRUE);
2252 return 0;
2255 c = g_utf8_get_char (p);
2258 switch (c)
2260 case 'a':
2261 if (systemtime.wDayOfWeek == 0)
2262 k = 6;
2263 else
2264 k = systemtime.wDayOfWeek - 1;
2265 n = GetLocaleInfoW (lcid, LOCALE_SABBREVDAYNAME1+k, NULL, 0);
2266 g_array_set_size (result, result->len + n);
2267 GetLocaleInfoW (lcid, LOCALE_SABBREVDAYNAME1+k, ((wchar_t *) result->data) + result->len - n, n);
2268 g_array_set_size (result, result->len - 1);
2269 break;
2270 case 'A':
2271 if (systemtime.wDayOfWeek == 0)
2272 k = 6;
2273 else
2274 k = systemtime.wDayOfWeek - 1;
2275 n = GetLocaleInfoW (lcid, LOCALE_SDAYNAME1+k, NULL, 0);
2276 g_array_set_size (result, result->len + n);
2277 GetLocaleInfoW (lcid, LOCALE_SDAYNAME1+k, ((wchar_t *) result->data) + result->len - n, n);
2278 g_array_set_size (result, result->len - 1);
2279 break;
2280 case 'b':
2281 case 'h':
2282 append_month_name (result, lcid, &systemtime, TRUE,
2283 modifier == 'O');
2284 break;
2285 case 'B':
2286 append_month_name (result, lcid, &systemtime, FALSE,
2287 modifier == 'O');
2288 break;
2289 case 'c':
2290 n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
2291 if (n > 0)
2293 g_array_set_size (result, result->len + n);
2294 GetDateFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
2295 g_array_set_size (result, result->len - 1);
2297 g_array_append_vals (result, L" ", 1);
2298 n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
2299 if (n > 0)
2301 g_array_set_size (result, result->len + n);
2302 GetTimeFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
2303 g_array_set_size (result, result->len - 1);
2305 break;
2306 case 'C':
2307 g_array_append_vals (result, digits + systemtime.wYear/1000, 1);
2308 g_array_append_vals (result, digits + (systemtime.wYear/1000)%10, 1);
2309 break;
2310 case 'd':
2311 g_array_append_vals (result, digits + systemtime.wDay/10, 1);
2312 g_array_append_vals (result, digits + systemtime.wDay%10, 1);
2313 break;
2314 case 'D':
2315 g_array_append_vals (result, digits + systemtime.wMonth/10, 1);
2316 g_array_append_vals (result, digits + systemtime.wMonth%10, 1);
2317 g_array_append_vals (result, L"/", 1);
2318 g_array_append_vals (result, digits + systemtime.wDay/10, 1);
2319 g_array_append_vals (result, digits + systemtime.wDay%10, 1);
2320 g_array_append_vals (result, L"/", 1);
2321 g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
2322 g_array_append_vals (result, digits + systemtime.wYear%10, 1);
2323 break;
2324 case 'e':
2325 if (systemtime.wDay >= 10)
2326 g_array_append_vals (result, digits + systemtime.wDay/10, 1);
2327 else
2328 g_array_append_vals (result, L" ", 1);
2329 g_array_append_vals (result, digits + systemtime.wDay%10, 1);
2330 break;
2332 /* A GDate has no time fields, so for now we can
2333 * hardcode all time conversions into zeros (or 12 for
2334 * %I). The alternative code snippets in the #else
2335 * branches are here ready to be taken into use when
2336 * needed by a g_strftime() or g_date_and_time_format()
2337 * or whatever.
2339 case 'H':
2340 #if 1
2341 g_array_append_vals (result, L"00", 2);
2342 #else
2343 g_array_append_vals (result, digits + systemtime.wHour/10, 1);
2344 g_array_append_vals (result, digits + systemtime.wHour%10, 1);
2345 #endif
2346 break;
2347 case 'I':
2348 #if 1
2349 g_array_append_vals (result, L"12", 2);
2350 #else
2351 if (systemtime.wHour == 0)
2352 g_array_append_vals (result, L"12", 2);
2353 else
2355 g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
2356 g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
2358 #endif
2359 break;
2360 case 'j':
2361 g_array_append_vals (result, digits + (tm->tm_yday+1)/100, 1);
2362 g_array_append_vals (result, digits + ((tm->tm_yday+1)/10)%10, 1);
2363 g_array_append_vals (result, digits + (tm->tm_yday+1)%10, 1);
2364 break;
2365 case 'm':
2366 g_array_append_vals (result, digits + systemtime.wMonth/10, 1);
2367 g_array_append_vals (result, digits + systemtime.wMonth%10, 1);
2368 break;
2369 case 'M':
2370 #if 1
2371 g_array_append_vals (result, L"00", 2);
2372 #else
2373 g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
2374 g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
2375 #endif
2376 break;
2377 case 'n':
2378 g_array_append_vals (result, L"\n", 1);
2379 break;
2380 case 'p':
2381 n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
2382 if (n > 0)
2384 g_array_set_size (result, result->len + n);
2385 GetTimeFormatW (lcid, 0, &systemtime, L"tt", ((wchar_t *) result->data) + result->len - n, n);
2386 g_array_set_size (result, result->len - 1);
2388 break;
2389 case 'r':
2390 /* This is a rather odd format. Hard to say what to do.
2391 * Let's always use the POSIX %I:%M:%S %p
2393 #if 1
2394 g_array_append_vals (result, L"12:00:00", 8);
2395 #else
2396 if (systemtime.wHour == 0)
2397 g_array_append_vals (result, L"12", 2);
2398 else
2400 g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
2401 g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
2403 g_array_append_vals (result, L":", 1);
2404 g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
2405 g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
2406 g_array_append_vals (result, L":", 1);
2407 g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
2408 g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
2409 g_array_append_vals (result, L" ", 1);
2410 #endif
2411 n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
2412 if (n > 0)
2414 g_array_set_size (result, result->len + n);
2415 GetTimeFormatW (lcid, 0, &systemtime, L"tt", ((wchar_t *) result->data) + result->len - n, n);
2416 g_array_set_size (result, result->len - 1);
2418 break;
2419 case 'R':
2420 #if 1
2421 g_array_append_vals (result, L"00:00", 5);
2422 #else
2423 g_array_append_vals (result, digits + systemtime.wHour/10, 1);
2424 g_array_append_vals (result, digits + systemtime.wHour%10, 1);
2425 g_array_append_vals (result, L":", 1);
2426 g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
2427 g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
2428 #endif
2429 break;
2430 case 'S':
2431 #if 1
2432 g_array_append_vals (result, L"00", 2);
2433 #else
2434 g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
2435 g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
2436 #endif
2437 break;
2438 case 't':
2439 g_array_append_vals (result, L"\t", 1);
2440 break;
2441 case 'T':
2442 #if 1
2443 g_array_append_vals (result, L"00:00:00", 8);
2444 #else
2445 g_array_append_vals (result, digits + systemtime.wHour/10, 1);
2446 g_array_append_vals (result, digits + systemtime.wHour%10, 1);
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 #endif
2454 break;
2455 case 'u':
2456 if (systemtime.wDayOfWeek == 0)
2457 g_array_append_vals (result, L"7", 1);
2458 else
2459 g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
2460 break;
2461 case 'U':
2462 n = g_date_get_sunday_week_of_year (d);
2463 g_array_append_vals (result, digits + n/10, 1);
2464 g_array_append_vals (result, digits + n%10, 1);
2465 break;
2466 case 'V':
2467 n = g_date_get_iso8601_week_of_year (d);
2468 g_array_append_vals (result, digits + n/10, 1);
2469 g_array_append_vals (result, digits + n%10, 1);
2470 break;
2471 case 'w':
2472 g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
2473 break;
2474 case 'W':
2475 n = g_date_get_monday_week_of_year (d);
2476 g_array_append_vals (result, digits + n/10, 1);
2477 g_array_append_vals (result, digits + n%10, 1);
2478 break;
2479 case 'x':
2480 n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
2481 if (n > 0)
2483 g_array_set_size (result, result->len + n);
2484 GetDateFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
2485 g_array_set_size (result, result->len - 1);
2487 break;
2488 case 'X':
2489 n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
2490 if (n > 0)
2492 g_array_set_size (result, result->len + n);
2493 GetTimeFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
2494 g_array_set_size (result, result->len - 1);
2496 break;
2497 case 'y':
2498 g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
2499 g_array_append_vals (result, digits + systemtime.wYear%10, 1);
2500 break;
2501 case 'Y':
2502 g_array_append_vals (result, digits + systemtime.wYear/1000, 1);
2503 g_array_append_vals (result, digits + (systemtime.wYear/100)%10, 1);
2504 g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
2505 g_array_append_vals (result, digits + systemtime.wYear%10, 1);
2506 break;
2507 case 'Z':
2508 n = GetTimeZoneInformation (&tzinfo);
2509 if (n == TIME_ZONE_ID_UNKNOWN)
2511 else if (n == TIME_ZONE_ID_STANDARD)
2512 g_array_append_vals (result, tzinfo.StandardName, wcslen (tzinfo.StandardName));
2513 else if (n == TIME_ZONE_ID_DAYLIGHT)
2514 g_array_append_vals (result, tzinfo.DaylightName, wcslen (tzinfo.DaylightName));
2515 break;
2516 case '%':
2517 g_array_append_vals (result, L"%", 1);
2518 break;
2521 else if (c <= 0xFFFF)
2523 wchar_t wc = c;
2524 g_array_append_vals (result, &wc, 1);
2526 else
2528 glong nwc;
2529 wchar_t *ws;
2531 ws = g_ucs4_to_utf16 (&c, 1, NULL, &nwc, NULL);
2532 g_array_append_vals (result, ws, nwc);
2533 g_free (ws);
2535 p = g_utf8_next_char (p);
2538 convbuf = g_utf16_to_utf8 ((wchar_t *) result->data, result->len, NULL, &convlen, NULL);
2539 g_array_free (result, TRUE);
2541 if (!convbuf)
2543 s[0] = '\0';
2544 return 0;
2547 if (slen <= convlen)
2549 /* Ensure only whole characters are copied into the buffer. */
2550 gchar *end = g_utf8_find_prev_char (convbuf, convbuf + slen);
2551 g_assert (end != NULL);
2552 convlen = end - convbuf;
2554 /* Return 0 because the buffer isn't large enough. */
2555 retval = 0;
2557 else
2558 retval = convlen;
2560 memcpy (s, convbuf, convlen);
2561 s[convlen] = '\0';
2562 g_free (convbuf);
2564 return retval;
2567 #endif
2570 * g_date_strftime:
2571 * @s: destination buffer
2572 * @slen: buffer size
2573 * @format: format string
2574 * @date: valid #GDate
2576 * Generates a printed representation of the date, in a
2577 * [locale][setlocale]-specific way.
2578 * Works just like the platform's C library strftime() function,
2579 * but only accepts date-related formats; time-related formats
2580 * give undefined results. Date must be valid. Unlike strftime()
2581 * (which uses the locale encoding), works on a UTF-8 format
2582 * string and stores a UTF-8 result.
2584 * This function does not provide any conversion specifiers in
2585 * addition to those implemented by the platform's C library.
2586 * For example, don't expect that using g_date_strftime() would
2587 * make the \%F provided by the C99 strftime() work on Windows
2588 * where the C library only complies to C89.
2590 * Returns: number of characters written to the buffer, or 0 the buffer was too small
2592 #pragma GCC diagnostic push
2593 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2595 gsize
2596 g_date_strftime (gchar *s,
2597 gsize slen,
2598 const gchar *format,
2599 const GDate *d)
2601 struct tm tm;
2602 #ifndef G_OS_WIN32
2603 gsize locale_format_len = 0;
2604 gchar *locale_format;
2605 gsize tmplen;
2606 gchar *tmpbuf;
2607 gsize tmpbufsize;
2608 gsize convlen = 0;
2609 gchar *convbuf;
2610 GError *error = NULL;
2611 gsize retval;
2612 #endif
2614 g_return_val_if_fail (g_date_valid (d), 0);
2615 g_return_val_if_fail (slen > 0, 0);
2616 g_return_val_if_fail (format != NULL, 0);
2617 g_return_val_if_fail (s != NULL, 0);
2619 g_date_to_struct_tm (d, &tm);
2621 #ifdef G_OS_WIN32
2622 if (!g_utf8_validate (format, -1, NULL))
2624 s[0] = '\0';
2625 return 0;
2627 return win32_strftime_helper (d, format, &tm, s, slen);
2628 #else
2630 locale_format = g_locale_from_utf8 (format, -1, NULL, &locale_format_len, &error);
2632 if (error)
2634 g_warning (G_STRLOC "Error converting format to locale encoding: %s", error->message);
2635 g_error_free (error);
2637 s[0] = '\0';
2638 return 0;
2641 tmpbufsize = MAX (128, locale_format_len * 2);
2642 while (TRUE)
2644 tmpbuf = g_malloc (tmpbufsize);
2646 /* Set the first byte to something other than '\0', to be able to
2647 * recognize whether strftime actually failed or just returned "".
2649 tmpbuf[0] = '\1';
2650 tmplen = strftime (tmpbuf, tmpbufsize, locale_format, &tm);
2652 if (tmplen == 0 && tmpbuf[0] != '\0')
2654 g_free (tmpbuf);
2655 tmpbufsize *= 2;
2657 if (tmpbufsize > 65536)
2659 g_warning (G_STRLOC "Maximum buffer size for g_date_strftime exceeded: giving up");
2660 g_free (locale_format);
2662 s[0] = '\0';
2663 return 0;
2666 else
2667 break;
2669 g_free (locale_format);
2671 convbuf = g_locale_to_utf8 (tmpbuf, tmplen, NULL, &convlen, &error);
2672 g_free (tmpbuf);
2674 if (error)
2676 g_warning (G_STRLOC "Error converting results of strftime to UTF-8: %s", error->message);
2677 g_error_free (error);
2679 s[0] = '\0';
2680 return 0;
2683 if (slen <= convlen)
2685 /* Ensure only whole characters are copied into the buffer.
2687 gchar *end = g_utf8_find_prev_char (convbuf, convbuf + slen);
2688 g_assert (end != NULL);
2689 convlen = end - convbuf;
2691 /* Return 0 because the buffer isn't large enough.
2693 retval = 0;
2695 else
2696 retval = convlen;
2698 memcpy (s, convbuf, convlen);
2699 s[convlen] = '\0';
2700 g_free (convbuf);
2702 return retval;
2703 #endif
2706 #pragma GCC diagnostic pop