Set up test environment properly
[platform/upstream/glib.git] / glib / gdatetime.c
1 /* gdatetime.c
2  *
3  * Copyright (C) 2009-2010 Christian Hergert <chris@dronelabs.com>
4  * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk>
5  * Copyright (C) 2010 Emmanuele Bassi <ebassi@linux.intel.com>
6  * Copyright © 2010 Codethink Limited
7  *
8  * This library is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License as
10  * published by the Free Software Foundation; either version 2.1 of the
11  * licence, or (at your option) any later version.
12  *
13  * This is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
16  * License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
21  * USA.
22  *
23  * Authors: Christian Hergert <chris@dronelabs.com>
24  *          Thiago Santos <thiago.sousa.santos@collabora.co.uk>
25  *          Emmanuele Bassi <ebassi@linux.intel.com>
26  *          Ryan Lortie <desrt@desrt.ca>
27  */
28
29 /* Algorithms within this file are based on the Calendar FAQ by
30  * Claus Tondering.  It can be found at
31  * http://www.tondering.dk/claus/cal/calendar29.txt
32  *
33  * Copyright and disclaimer
34  * ------------------------
35  *   This document is Copyright (C) 2008 by Claus Tondering.
36  *   E-mail: claus@tondering.dk. (Please include the word
37  *   "calendar" in the subject line.)
38  *   The document may be freely distributed, provided this
39  *   copyright notice is included and no money is charged for
40  *   the document.
41  *
42  *   This document is provided "as is". No warranties are made as
43  *   to its correctness.
44  */
45
46 /* Prologue {{{1 */
47
48 #include "config.h"
49
50 #include <stdlib.h>
51 #include <string.h>
52
53 #ifdef HAVE_UNISTD_H
54 #include <unistd.h>
55 #endif
56
57 #ifdef HAVE_LANGINFO_TIME
58 #include <langinfo.h>
59 #endif
60
61 #include "gdatetime.h"
62
63 #include "gslice.h"
64 #include "gatomic.h"
65 #include "gcharset.h"
66 #include "gconvert.h"
67 #include "gfileutils.h"
68 #include "ghash.h"
69 #include "gmain.h"
70 #include "gmappedfile.h"
71 #include "gstrfuncs.h"
72 #include "gtestutils.h"
73 #include "gthread.h"
74 #include "gtimezone.h"
75
76 #include "glibintl.h"
77
78 #ifndef G_OS_WIN32
79 #include <sys/time.h>
80 #include <time.h>
81 #endif /* !G_OS_WIN32 */
82
83 /**
84  * SECTION:date-time
85  * @title: GDateTime
86  * @short_description: a structure representing Date and Time
87  * @see_also: #GTimeZone
88  *
89  * #GDateTime is a structure that combines a Gregorian date and time
90  * into a single structure.  It provides many conversion and methods to
91  * manipulate dates and times.  Time precision is provided down to
92  * microseconds and the time can range (proleptically) from 0001-01-01
93  * 00:00:00 to 9999-12-31 23:59:59.999999.  #GDateTime follows POSIX
94  * time in the sense that it is oblivious to leap seconds.
95  *
96  * #GDateTime is an immutable object; once it has been created it cannot
97  * be modified further.  All modifiers will create a new #GDateTime.
98  * Nearly all such functions can fail due to the date or time going out
99  * of range, in which case %NULL will be returned.
100  *
101  * #GDateTime is reference counted: the reference count is increased by calling
102  * g_date_time_ref() and decreased by calling g_date_time_unref(). When the
103  * reference count drops to 0, the resources allocated by the #GDateTime
104  * structure are released.
105  *
106  * Many parts of the API may produce non-obvious results.  As an
107  * example, adding two months to January 31st will yield March 31st
108  * whereas adding one month and then one month again will yield either
109  * March 28th or March 29th.  Also note that adding 24 hours is not
110  * always the same as adding one day (since days containing daylight
111  * savings time transitions are either 23 or 25 hours in length).
112  *
113  * #GDateTime is available since GLib 2.26.
114  */
115
116 struct _GDateTime
117 {
118   /* Microsecond timekeeping within Day */
119   guint64 usec;
120
121   /* TimeZone information */
122   GTimeZone *tz;
123   gint interval;
124
125   /* 1 is 0001-01-01 in Proleptic Gregorian */
126   gint32 days;
127
128   volatile gint ref_count;
129 };
130
131 /* Time conversion {{{1 */
132
133 #define UNIX_EPOCH_START     719163
134 #define INSTANT_TO_UNIX(instant) \
135   ((instant)/USEC_PER_SECOND - UNIX_EPOCH_START * SEC_PER_DAY)
136 #define UNIX_TO_INSTANT(unix) \
137   (((unix) + UNIX_EPOCH_START * SEC_PER_DAY) * USEC_PER_SECOND)
138
139 #define DAYS_IN_4YEARS    1461    /* days in 4 years */
140 #define DAYS_IN_100YEARS  36524   /* days in 100 years */
141 #define DAYS_IN_400YEARS  146097  /* days in 400 years  */
142
143 #define USEC_PER_SECOND      (G_GINT64_CONSTANT (1000000))
144 #define USEC_PER_MINUTE      (G_GINT64_CONSTANT (60000000))
145 #define USEC_PER_HOUR        (G_GINT64_CONSTANT (3600000000))
146 #define USEC_PER_MILLISECOND (G_GINT64_CONSTANT (1000))
147 #define USEC_PER_DAY         (G_GINT64_CONSTANT (86400000000))
148 #define SEC_PER_DAY          (G_GINT64_CONSTANT (86400))
149
150 #define SECS_PER_MINUTE (60)
151 #define SECS_PER_HOUR   (60 * SECS_PER_MINUTE)
152 #define SECS_PER_DAY    (24 * SECS_PER_HOUR)
153 #define SECS_PER_YEAR   (365 * SECS_PER_DAY)
154 #define SECS_PER_JULIAN (DAYS_PER_PERIOD * SECS_PER_DAY)
155
156 #define GREGORIAN_LEAP(y)    ((((y) % 4) == 0) && (!((((y) % 100) == 0) && (((y) % 400) != 0))))
157 #define JULIAN_YEAR(d)       ((d)->julian / 365.25)
158 #define DAYS_PER_PERIOD      (G_GINT64_CONSTANT (2914695))
159
160 static const guint16 days_in_months[2][13] =
161 {
162   { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
163   { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
164 };
165
166 static const guint16 days_in_year[2][13] =
167 {
168   {  0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
169   {  0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
170 };
171
172 #ifdef HAVE_LANGINFO_TIME
173
174 #define GET_AMPM(d) ((g_date_time_get_hour (d) < 12) ? \
175                      nl_langinfo (AM_STR) : \
176                      nl_langinfo (PM_STR))
177
178 #define PREFERRED_DATE_TIME_FMT nl_langinfo (D_T_FMT)
179 #define PREFERRED_DATE_FMT nl_langinfo (D_FMT)
180 #define PREFERRED_TIME_FMT nl_langinfo (T_FMT)
181 #define PREFERRED_TIME_FMT nl_langinfo (T_FMT)
182 #define PREFERRED_12HR_TIME_FMT nl_langinfo (T_FMT_AMPM)
183
184 static const gint weekday_item[2][7] =
185 {
186   { ABDAY_2, ABDAY_3, ABDAY_4, ABDAY_5, ABDAY_6, ABDAY_7, ABDAY_1 },
187   { DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7, DAY_1 }
188 };
189
190 static const gint month_item[2][12] =
191 {
192   { ABMON_1, ABMON_2, ABMON_3, ABMON_4, ABMON_5, ABMON_6, ABMON_7, ABMON_8, ABMON_9, ABMON_10, ABMON_11, ABMON_12 },
193   { MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7, MON_8, MON_9, MON_10, MON_11, MON_12 },
194 };
195
196 #define WEEKDAY_ABBR(d) nl_langinfo (weekday_item[0][g_date_time_get_day_of_week (d) - 1])
197 #define WEEKDAY_FULL(d) nl_langinfo (weekday_item[1][g_date_time_get_day_of_week (d) - 1])
198 #define MONTH_ABBR(d) nl_langinfo (month_item[0][g_date_time_get_month (d) - 1])
199 #define MONTH_FULL(d) nl_langinfo (month_item[1][g_date_time_get_month (d) - 1])
200
201 #else
202
203 #define GET_AMPM(d)          ((g_date_time_get_hour (d) < 12)  \
204                                        /* Translators: 'before midday' indicator */ \
205                                 ? C_("GDateTime", "AM") \
206                                   /* Translators: 'after midday' indicator */ \
207                                 : C_("GDateTime", "PM"))
208
209 /* Translators: this is the preferred format for expressing the date and the time */
210 #define PREFERRED_DATE_TIME_FMT C_("GDateTime", "%a %b %e %H:%M:%S %Y")
211
212 /* Translators: this is the preferred format for expressing the date */
213 #define PREFERRED_DATE_FMT C_("GDateTime", "%m/%d/%y")
214
215 /* Translators: this is the preferred format for expressing the time */
216 #define PREFERRED_TIME_FMT C_("GDateTime", "%H:%M:%S")
217
218 /* Translators: this is the preferred format for expressing 12 hour time */
219 #define PREFERRED_12HR_TIME_FMT C_("GDateTime", "%I:%M:%S %p")
220
221 #define WEEKDAY_ABBR(d)       (get_weekday_name_abbr (g_date_time_get_day_of_week (d)))
222 #define WEEKDAY_FULL(d)       (get_weekday_name (g_date_time_get_day_of_week (d)))
223 #define MONTH_ABBR(d)         (get_month_name_abbr (g_date_time_get_month (d)))
224 #define MONTH_FULL(d)         (get_month_name (g_date_time_get_month (d)))
225
226 static const gchar *
227 get_month_name (gint month)
228 {
229   switch (month)
230     {
231     case 1:
232       return C_("full month name", "January");
233     case 2:
234       return C_("full month name", "February");
235     case 3:
236       return C_("full month name", "March");
237     case 4:
238       return C_("full month name", "April");
239     case 5:
240       return C_("full month name", "May");
241     case 6:
242       return C_("full month name", "June");
243     case 7:
244       return C_("full month name", "July");
245     case 8:
246       return C_("full month name", "August");
247     case 9:
248       return C_("full month name", "September");
249     case 10:
250       return C_("full month name", "October");
251     case 11:
252       return C_("full month name", "November");
253     case 12:
254       return C_("full month name", "December");
255
256     default:
257       g_warning ("Invalid month number %d", month);
258     }
259
260   return NULL;
261 }
262
263 static const gchar *
264 get_month_name_abbr (gint month)
265 {
266   switch (month)
267     {
268     case 1:
269       return C_("abbreviated month name", "Jan");
270     case 2:
271       return C_("abbreviated month name", "Feb");
272     case 3:
273       return C_("abbreviated month name", "Mar");
274     case 4:
275       return C_("abbreviated month name", "Apr");
276     case 5:
277       return C_("abbreviated month name", "May");
278     case 6:
279       return C_("abbreviated month name", "Jun");
280     case 7:
281       return C_("abbreviated month name", "Jul");
282     case 8:
283       return C_("abbreviated month name", "Aug");
284     case 9:
285       return C_("abbreviated month name", "Sep");
286     case 10:
287       return C_("abbreviated month name", "Oct");
288     case 11:
289       return C_("abbreviated month name", "Nov");
290     case 12:
291       return C_("abbreviated month name", "Dec");
292
293     default:
294       g_warning ("Invalid month number %d", month);
295     }
296
297   return NULL;
298 }
299
300 static const gchar *
301 get_weekday_name (gint day)
302 {
303   switch (day)
304     {
305     case 1:
306       return C_("full weekday name", "Monday");
307     case 2:
308       return C_("full weekday name", "Tuesday");
309     case 3:
310       return C_("full weekday name", "Wednesday");
311     case 4:
312       return C_("full weekday name", "Thursday");
313     case 5:
314       return C_("full weekday name", "Friday");
315     case 6:
316       return C_("full weekday name", "Saturday");
317     case 7:
318       return C_("full weekday name", "Sunday");
319
320     default:
321       g_warning ("Invalid week day number %d", day);
322     }
323
324   return NULL;
325 }
326
327 static const gchar *
328 get_weekday_name_abbr (gint day)
329 {
330   switch (day)
331     {
332     case 1:
333       return C_("abbreviated weekday name", "Mon");
334     case 2:
335       return C_("abbreviated weekday name", "Tue");
336     case 3:
337       return C_("abbreviated weekday name", "Wed");
338     case 4:
339       return C_("abbreviated weekday name", "Thu");
340     case 5:
341       return C_("abbreviated weekday name", "Fri");
342     case 6:
343       return C_("abbreviated weekday name", "Sat");
344     case 7:
345       return C_("abbreviated weekday name", "Sun");
346
347     default:
348       g_warning ("Invalid week day number %d", day);
349     }
350
351   return NULL;
352 }
353
354 #endif  /* HAVE_LANGINFO_TIME */
355
356 static inline gint
357 ymd_to_days (gint year,
358              gint month,
359              gint day)
360 {
361   gint64 days;
362
363   days = (year - 1) * 365 + ((year - 1) / 4) - ((year - 1) / 100)
364       + ((year - 1) / 400);
365
366   days += days_in_year[0][month - 1];
367   if (GREGORIAN_LEAP (year) && month > 2)
368     day++;
369
370   days += day;
371
372   return days;
373 }
374
375 static void
376 g_date_time_get_week_number (GDateTime *datetime,
377                              gint      *week_number,
378                              gint      *day_of_week,
379                              gint      *day_of_year)
380 {
381   gint a, b, c, d, e, f, g, n, s, month, day, year;
382
383   g_date_time_get_ymd (datetime, &year, &month, &day);
384
385   if (month <= 2)
386     {
387       a = g_date_time_get_year (datetime) - 1;
388       b = (a / 4) - (a / 100) + (a / 400);
389       c = ((a - 1) / 4) - ((a - 1) / 100) + ((a - 1) / 400);
390       s = b - c;
391       e = 0;
392       f = day - 1 + (31 * (month - 1));
393     }
394   else
395     {
396       a = year;
397       b = (a / 4) - (a / 100) + (a / 400);
398       c = ((a - 1) / 4) - ((a - 1) / 100) + ((a - 1) / 400);
399       s = b - c;
400       e = s + 1;
401       f = day + (((153 * (month - 3)) + 2) / 5) + 58 + s;
402     }
403
404   g = (a + b) % 7;
405   d = (f + g - e) % 7;
406   n = f + 3 - d;
407
408   if (week_number)
409     {
410       if (n < 0)
411         *week_number = 53 - ((g - s) / 5);
412       else if (n > 364 + s)
413         *week_number = 1;
414       else
415         *week_number = (n / 7) + 1;
416     }
417
418   if (day_of_week)
419     *day_of_week = d + 1;
420
421   if (day_of_year)
422     *day_of_year = f + 1;
423 }
424
425 /* Lifecycle {{{1 */
426
427 static GDateTime *
428 g_date_time_alloc (GTimeZone *tz)
429 {
430   GDateTime *datetime;
431
432   datetime = g_slice_new0 (GDateTime);
433   datetime->tz = g_time_zone_ref (tz);
434   datetime->ref_count = 1;
435
436   return datetime;
437 }
438
439 /**
440  * g_date_time_ref:
441  * @datetime: a #GDateTime
442  *
443  * Atomically increments the reference count of @datetime by one.
444  *
445  * Return value: the #GDateTime with the reference count increased
446  *
447  * Since: 2.26
448  */
449 GDateTime *
450 g_date_time_ref (GDateTime *datetime)
451 {
452   g_return_val_if_fail (datetime != NULL, NULL);
453   g_return_val_if_fail (datetime->ref_count > 0, NULL);
454
455   g_atomic_int_inc (&datetime->ref_count);
456
457   return datetime;
458 }
459
460 /**
461  * g_date_time_unref:
462  * @datetime: a #GDateTime
463  *
464  * Atomically decrements the reference count of @datetime by one.
465  *
466  * When the reference count reaches zero, the resources allocated by
467  * @datetime are freed
468  *
469  * Since: 2.26
470  */
471 void
472 g_date_time_unref (GDateTime *datetime)
473 {
474   g_return_if_fail (datetime != NULL);
475   g_return_if_fail (datetime->ref_count > 0);
476
477   if (g_atomic_int_dec_and_test (&datetime->ref_count))
478     {
479       g_time_zone_unref (datetime->tz);
480       g_slice_free (GDateTime, datetime);
481     }
482 }
483
484 /* Internal state transformers {{{1 */
485 /*< internal >
486  * g_date_time_to_instant:
487  * @datetime: a #GDateTime
488  *
489  * Convert a @datetime into an instant.
490  *
491  * An instant is a number that uniquely describes a particular
492  * microsecond in time, taking time zone considerations into account.
493  * (ie: "03:00 -0400" is the same instant as "02:00 -0500").
494  *
495  * An instant is always positive but we use a signed return value to
496  * avoid troubles with C.
497  */
498 static gint64
499 g_date_time_to_instant (GDateTime *datetime)
500 {
501   gint64 offset;
502
503   offset = g_time_zone_get_offset (datetime->tz, datetime->interval);
504   offset *= USEC_PER_SECOND;
505
506   return datetime->days * USEC_PER_DAY + datetime->usec - offset;
507 }
508
509 /*< internal >
510  * g_date_time_from_instant:
511  * @tz: a #GTimeZone
512  * @instant: a instant in time
513  *
514  * Creates a #GDateTime from a time zone and an instant.
515  *
516  * This might fail if the time ends up being out of range.
517  */
518 static GDateTime *
519 g_date_time_from_instant (GTimeZone *tz,
520                           gint64     instant)
521 {
522   GDateTime *datetime;
523   gint64 offset;
524
525   if (instant < 0 || instant > G_GINT64_CONSTANT (1000000000000000000))
526     return NULL;
527
528   datetime = g_date_time_alloc (tz);
529   datetime->interval = g_time_zone_find_interval (tz,
530                                                   G_TIME_TYPE_UNIVERSAL,
531                                                   INSTANT_TO_UNIX (instant));
532   offset = g_time_zone_get_offset (datetime->tz, datetime->interval);
533   offset *= USEC_PER_SECOND;
534
535   instant += offset;
536
537   datetime->days = instant / USEC_PER_DAY;
538   datetime->usec = instant % USEC_PER_DAY;
539
540   if (datetime->days < 1 || 3652059 < datetime->days)
541     {
542       g_date_time_unref (datetime);
543       datetime = NULL;
544     }
545
546   return datetime;
547 }
548
549
550 /*< internal >
551  * g_date_time_deal_with_date_change:
552  * @datetime: a #GDateTime
553  *
554  * This function should be called whenever the date changes by adding
555  * days, months or years.  It does three things.
556  *
557  * First, we ensure that the date falls between 0001-01-01 and
558  * 9999-12-31 and return %FALSE if it does not.
559  *
560  * Next we update the ->interval field.
561  *
562  * Finally, we ensure that the resulting date and time pair exists (by
563  * ensuring that our time zone has an interval containing it) and
564  * adjusting as required.  For example, if we have the time 02:30:00 on
565  * March 13 2010 in Toronto and we add 1 day to it, we would end up with
566  * 2:30am on March 14th, which doesn't exist.  In that case, we bump the
567  * time up to 3:00am.
568  */
569 static gboolean
570 g_date_time_deal_with_date_change (GDateTime *datetime)
571 {
572   GTimeType was_dst;
573   gint64 full_time;
574   gint64 usec;
575
576   if (datetime->days < 1 || datetime->days > 3652059)
577     return FALSE;
578
579   was_dst = g_time_zone_is_dst (datetime->tz, datetime->interval);
580
581   full_time = datetime->days * USEC_PER_DAY + datetime->usec;
582
583
584   usec = full_time % USEC_PER_SECOND;
585   full_time /= USEC_PER_SECOND;
586   full_time -= UNIX_EPOCH_START * SEC_PER_DAY;
587
588   datetime->interval = g_time_zone_adjust_time (datetime->tz,
589                                                 was_dst,
590                                                 &full_time);
591   full_time += UNIX_EPOCH_START * SEC_PER_DAY;
592   full_time *= USEC_PER_SECOND;
593   full_time += usec;
594
595   datetime->days = full_time / USEC_PER_DAY;
596   datetime->usec = full_time % USEC_PER_DAY;
597
598   /* maybe daylight time caused us to shift to a different day,
599    * but it definitely didn't push us into a different year */
600   return TRUE;
601 }
602
603 static GDateTime *
604 g_date_time_replace_days (GDateTime *datetime,
605                           gint       days)
606 {
607   GDateTime *new;
608
609   new = g_date_time_alloc (datetime->tz);
610   new->interval = datetime->interval;
611   new->usec = datetime->usec;
612   new->days = days;
613
614   if (!g_date_time_deal_with_date_change (new))
615     {
616       g_date_time_unref (new);
617       new = NULL;
618     }
619
620   return new;
621 }
622
623 /* now/unix/timeval Constructors {{{1 */
624
625 /*< internal >
626  * g_date_time_new_from_timeval:
627  * @tz: a #GTimeZone
628  * @tv: a #GTimeVal
629  *
630  * Creates a #GDateTime corresponding to the given #GTimeVal @tv in the
631  * given time zone @tz.
632  *
633  * The time contained in a #GTimeVal is always stored in the form of
634  * seconds elapsed since 1970-01-01 00:00:00 UTC, regardless of the
635  * given time zone.
636  *
637  * This call can fail (returning %NULL) if @tv represents a time outside
638  * of the supported range of #GDateTime.
639  *
640  * You should release the return value by calling g_date_time_unref()
641  * when you are done with it.
642  *
643  * Returns: a new #GDateTime, or %NULL
644  *
645  * Since: 2.26
646  **/
647 static GDateTime *
648 g_date_time_new_from_timeval (GTimeZone      *tz,
649                               const GTimeVal *tv)
650 {
651   return g_date_time_from_instant (tz, tv->tv_usec +
652                                    UNIX_TO_INSTANT (tv->tv_sec));
653 }
654
655 /*< internal >
656  * g_date_time_new_from_unix:
657  * @tz: a #GTimeZone
658  * @t: the Unix time
659  *
660  * Creates a #GDateTime corresponding to the given Unix time @t in the
661  * given time zone @tz.
662  *
663  * Unix time is the number of seconds that have elapsed since 1970-01-01
664  * 00:00:00 UTC, regardless of the time zone given.
665  *
666  * This call can fail (returning %NULL) if @t represents a time outside
667  * of the supported range of #GDateTime.
668  *
669  * You should release the return value by calling g_date_time_unref()
670  * when you are done with it.
671  *
672  * Returns: a new #GDateTime, or %NULL
673  *
674  * Since: 2.26
675  **/
676 static GDateTime *
677 g_date_time_new_from_unix (GTimeZone *tz,
678                            gint64     secs)
679 {
680   return g_date_time_from_instant (tz, UNIX_TO_INSTANT (secs));
681 }
682
683 /**
684  * g_date_time_new_now:
685  * @tz: a #GTimeZone
686  *
687  * Creates a #GDateTime corresponding to this exact instant in the given
688  * time zone @tz.  The time is as accurate as the system allows, to a
689  * maximum accuracy of 1 microsecond.
690  *
691  * This function will always succeed unless the system clock is set to
692  * truly insane values (or unless GLib is still being used after the
693  * year 9999).
694  *
695  * You should release the return value by calling g_date_time_unref()
696  * when you are done with it.
697  *
698  * Returns: a new #GDateTime, or %NULL
699  *
700  * Since: 2.26
701  **/
702 GDateTime *
703 g_date_time_new_now (GTimeZone *tz)
704 {
705   GTimeVal tv;
706
707   g_get_current_time (&tv);
708
709   return g_date_time_new_from_timeval (tz, &tv);
710 }
711
712 /**
713  * g_date_time_new_now_local:
714  *
715  * Creates a #GDateTime corresponding to this exact instant in the local
716  * time zone.
717  *
718  * This is equivalent to calling g_date_time_new_now() with the time
719  * zone returned by g_time_zone_new_local().
720  *
721  * Returns: a new #GDateTime, or %NULL
722  *
723  * Since: 2.26
724  **/
725 GDateTime *
726 g_date_time_new_now_local (void)
727 {
728   GDateTime *datetime;
729   GTimeZone *local;
730
731   local = g_time_zone_new_local ();
732   datetime = g_date_time_new_now (local);
733   g_time_zone_unref (local);
734
735   return datetime;
736 }
737
738 /**
739  * g_date_time_new_now_utc:
740  *
741  * Creates a #GDateTime corresponding to this exact instant in UTC.
742  *
743  * This is equivalent to calling g_date_time_new_now() with the time
744  * zone returned by g_time_zone_new_utc().
745  *
746  * Returns: a new #GDateTime, or %NULL
747  *
748  * Since: 2.26
749  **/
750 GDateTime *
751 g_date_time_new_now_utc (void)
752 {
753   GDateTime *datetime;
754   GTimeZone *utc;
755
756   utc = g_time_zone_new_utc ();
757   datetime = g_date_time_new_now (utc);
758   g_time_zone_unref (utc);
759
760   return datetime;
761 }
762
763 /**
764  * g_date_time_new_from_unix_local:
765  * @t: the Unix time
766  *
767  * Creates a #GDateTime corresponding to the given Unix time @t in the
768  * local time zone.
769  *
770  * Unix time is the number of seconds that have elapsed since 1970-01-01
771  * 00:00:00 UTC, regardless of the local time offset.
772  *
773  * This call can fail (returning %NULL) if @t represents a time outside
774  * of the supported range of #GDateTime.
775  *
776  * You should release the return value by calling g_date_time_unref()
777  * when you are done with it.
778  *
779  * Returns: a new #GDateTime, or %NULL
780  *
781  * Since: 2.26
782  **/
783 GDateTime *
784 g_date_time_new_from_unix_local (gint64 t)
785 {
786   GDateTime *datetime;
787   GTimeZone *local;
788
789   local = g_time_zone_new_local ();
790   datetime = g_date_time_new_from_unix (local, t);
791   g_time_zone_unref (local);
792
793   return datetime;
794 }
795
796 /**
797  * g_date_time_new_from_unix_utc:
798  * @t: the Unix time
799  *
800  * Creates a #GDateTime corresponding to the given Unix time @t in UTC.
801  *
802  * Unix time is the number of seconds that have elapsed since 1970-01-01
803  * 00:00:00 UTC.
804  *
805  * This call can fail (returning %NULL) if @t represents a time outside
806  * of the supported range of #GDateTime.
807  *
808  * You should release the return value by calling g_date_time_unref()
809  * when you are done with it.
810  *
811  * Returns: a new #GDateTime, or %NULL
812  *
813  * Since: 2.26
814  **/
815 GDateTime *
816 g_date_time_new_from_unix_utc (gint64 t)
817 {
818   GDateTime *datetime;
819   GTimeZone *utc;
820
821   utc = g_time_zone_new_utc ();
822   datetime = g_date_time_new_from_unix (utc, t);
823   g_time_zone_unref (utc);
824
825   return datetime;
826 }
827
828 /**
829  * g_date_time_new_from_timeval_local:
830  * @tv: a #GTimeVal
831  *
832  * Creates a #GDateTime corresponding to the given #GTimeVal @tv in the
833  * local time zone.
834  *
835  * The time contained in a #GTimeVal is always stored in the form of
836  * seconds elapsed since 1970-01-01 00:00:00 UTC, regardless of the
837  * local time offset.
838  *
839  * This call can fail (returning %NULL) if @tv represents a time outside
840  * of the supported range of #GDateTime.
841  *
842  * You should release the return value by calling g_date_time_unref()
843  * when you are done with it.
844  *
845  * Returns: a new #GDateTime, or %NULL
846  *
847  * Since: 2.26
848  **/
849 GDateTime *
850 g_date_time_new_from_timeval_local (const GTimeVal *tv)
851 {
852   GDateTime *datetime;
853   GTimeZone *local;
854
855   local = g_time_zone_new_local ();
856   datetime = g_date_time_new_from_timeval (local, tv);
857   g_time_zone_unref (local);
858
859   return datetime;
860 }
861
862 /**
863  * g_date_time_new_from_timeval_utc:
864  * @tv: a #GTimeVal
865  *
866  * Creates a #GDateTime corresponding to the given #GTimeVal @tv in UTC.
867  *
868  * The time contained in a #GTimeVal is always stored in the form of
869  * seconds elapsed since 1970-01-01 00:00:00 UTC.
870  *
871  * This call can fail (returning %NULL) if @tv represents a time outside
872  * of the supported range of #GDateTime.
873  *
874  * You should release the return value by calling g_date_time_unref()
875  * when you are done with it.
876  *
877  * Returns: a new #GDateTime, or %NULL
878  *
879  * Since: 2.26
880  **/
881 GDateTime *
882 g_date_time_new_from_timeval_utc (const GTimeVal *tv)
883 {
884   GDateTime *datetime;
885   GTimeZone *utc;
886
887   utc = g_time_zone_new_utc ();
888   datetime = g_date_time_new_from_timeval (utc, tv);
889   g_time_zone_unref (utc);
890
891   return datetime;
892 }
893
894 /* full new functions {{{1 */
895
896 /**
897  * g_date_time_new:
898  * @tz: a #GTimeZone
899  * @year: the year component of the date
900  * @month: the month component of the date
901  * @day: the day component of the date
902  * @hour: the hour component of the date
903  * @minute: the minute component of the date
904  * @seconds: the number of seconds past the minute
905  *
906  * Creates a new #GDateTime corresponding to the given date and time in
907  * the time zone @tz.
908  *
909  * The @year must be between 1 and 9999, @month between 1 and 12 and @day
910  * between 1 and 28, 29, 30 or 31 depending on the month and the year.
911  *
912  * @hour must be between 0 and 23 and @minute must be between 0 and 59.
913  *
914  * @seconds must be at least 0.0 and must be strictly less than 60.0.
915  * It will be rounded down to the nearest microsecond.
916  *
917  * If the given time is not representable in the given time zone (for
918  * example, 02:30 on March 14th 2010 in Toronto, due to daylight savings
919  * time) then the time will be rounded up to the nearest existing time
920  * (in this case, 03:00).  If this matters to you then you should verify
921  * the return value for containing the same as the numbers you gave.
922  *
923  * In the case that the given time is ambiguous in the given time zone
924  * (for example, 01:30 on November 7th 2010 in Toronto, due to daylight
925  * savings time) then the time falling within standard (ie:
926  * non-daylight) time is taken.
927  *
928  * It not considered a programmer error for the values to this function
929  * to be out of range, but in the case that they are, the function will
930  * return %NULL.
931  *
932  * You should release the return value by calling g_date_time_unref()
933  * when you are done with it.
934  *
935  * Returns: a new #GDateTime, or %NULL
936  *
937  * Since: 2.26
938  **/
939 GDateTime *
940 g_date_time_new (GTimeZone *tz,
941                  gint       year,
942                  gint       month,
943                  gint       day,
944                  gint       hour,
945                  gint       minute,
946                  gdouble    seconds)
947 {
948   GDateTime *datetime;
949   gint64 full_time;
950
951   if (year < 1 || year > 9999 ||
952       month < 1 || month > 12 ||
953       day < 1 || day > 31 ||
954       hour < 0 || hour > 23 ||
955       minute < 0 || minute > 59 ||
956       seconds < 0.0 || seconds >= 60.0)
957     return NULL;
958
959   datetime = g_date_time_alloc (tz);
960   datetime->days = ymd_to_days (year, month, day);
961   datetime->usec = (hour   * USEC_PER_HOUR)
962                  + (minute * USEC_PER_MINUTE)
963                  + (gint64) (seconds * USEC_PER_SECOND);
964
965   full_time = SEC_PER_DAY *
966                 (ymd_to_days (year, month, day) - UNIX_EPOCH_START) +
967               SECS_PER_HOUR * hour +
968               SECS_PER_MINUTE * minute +
969               (int) seconds;
970
971   datetime->interval = g_time_zone_adjust_time (datetime->tz,
972                                                 G_TIME_TYPE_STANDARD,
973                                                 &full_time);
974
975   full_time += UNIX_EPOCH_START * SEC_PER_DAY;
976   datetime->days = full_time / SEC_PER_DAY;
977   datetime->usec = (full_time % SEC_PER_DAY) * USEC_PER_SECOND;
978   datetime->usec += ((int) (seconds * USEC_PER_SECOND)) % USEC_PER_SECOND;
979
980   return datetime;
981 }
982
983 /**
984  * g_date_time_new_local:
985  * @year: the year component of the date
986  * @month: the month component of the date
987  * @day: the day component of the date
988  * @hour: the hour component of the date
989  * @minute: the minute component of the date
990  * @seconds: the number of seconds past the minute
991  *
992  * Creates a new #GDateTime corresponding to the given date and time in
993  * the local time zone.
994  *
995  * This call is equivalent to calling g_date_time_new() with the time
996  * zone returned by g_time_zone_new_local().
997  *
998  * Returns: a #GDateTime, or %NULL
999  *
1000  * Since: 2.26
1001  **/
1002 GDateTime *
1003 g_date_time_new_local (gint    year,
1004                        gint    month,
1005                        gint    day,
1006                        gint    hour,
1007                        gint    minute,
1008                        gdouble seconds)
1009 {
1010   GDateTime *datetime;
1011   GTimeZone *local;
1012
1013   local = g_time_zone_new_local ();
1014   datetime = g_date_time_new (local, year, month, day, hour, minute, seconds);
1015   g_time_zone_unref (local);
1016
1017   return datetime;
1018 }
1019
1020 /**
1021  * g_date_time_new_utc:
1022  * @year: the year component of the date
1023  * @month: the month component of the date
1024  * @day: the day component of the date
1025  * @hour: the hour component of the date
1026  * @minute: the minute component of the date
1027  * @seconds: the number of seconds past the minute
1028  *
1029  * Creates a new #GDateTime corresponding to the given date and time in
1030  * UTC.
1031  *
1032  * This call is equivalent to calling g_date_time_new() with the time
1033  * zone returned by g_time_zone_new_utc().
1034  *
1035  * Returns: a #GDateTime, or %NULL
1036  *
1037  * Since: 2.26
1038  **/
1039 GDateTime *
1040 g_date_time_new_utc (gint    year,
1041                      gint    month,
1042                      gint    day,
1043                      gint    hour,
1044                      gint    minute,
1045                      gdouble seconds)
1046 {
1047   GDateTime *datetime;
1048   GTimeZone *utc;
1049
1050   utc = g_time_zone_new_utc ();
1051   datetime = g_date_time_new (utc, year, month, day, hour, minute, seconds);
1052   g_time_zone_unref (utc);
1053
1054   return datetime;
1055 }
1056
1057 /* Adders {{{1 */
1058
1059 /**
1060  * g_date_time_add:
1061  * @datetime: a #GDateTime
1062  * @timespan: a #GTimeSpan
1063  *
1064  * Creates a copy of @datetime and adds the specified timespan to the copy.
1065  *
1066  * Return value: the newly created #GDateTime which should be freed with
1067  *   g_date_time_unref().
1068  *
1069  * Since: 2.26
1070  */
1071 GDateTime*
1072 g_date_time_add (GDateTime *datetime,
1073                  GTimeSpan  timespan)
1074 {
1075   return g_date_time_from_instant (datetime->tz, timespan +
1076                                    g_date_time_to_instant (datetime));
1077 }
1078
1079 /**
1080  * g_date_time_add_years:
1081  * @datetime: a #GDateTime
1082  * @years: the number of years
1083  *
1084  * Creates a copy of @datetime and adds the specified number of years to the
1085  * copy.
1086  *
1087  * Return value: the newly created #GDateTime which should be freed with
1088  *   g_date_time_unref().
1089  *
1090  * Since: 2.26
1091  */
1092 GDateTime *
1093 g_date_time_add_years (GDateTime *datetime,
1094                        gint       years)
1095 {
1096   gint year, month, day;
1097
1098   g_return_val_if_fail (datetime != NULL, NULL);
1099
1100   if (years < -10000 || years > 10000)
1101     return NULL;
1102
1103   g_date_time_get_ymd (datetime, &year, &month, &day);
1104   year += years;
1105
1106   /* only possible issue is if we've entered a year with no February 29
1107    */
1108   if (month == 2 && day == 29 && !GREGORIAN_LEAP (year))
1109     day = 28;
1110
1111   return g_date_time_replace_days (datetime, ymd_to_days (year, month, day));
1112 }
1113
1114 /**
1115  * g_date_time_add_months:
1116  * @datetime: a #GDateTime
1117  * @months: the number of months
1118  *
1119  * Creates a copy of @datetime and adds the specified number of months to the
1120  * copy.
1121  *
1122  * Return value: the newly created #GDateTime which should be freed with
1123  *   g_date_time_unref().
1124  *
1125  * Since: 2.26
1126  */
1127 GDateTime*
1128 g_date_time_add_months (GDateTime *datetime,
1129                         gint       months)
1130 {
1131   gint year, month, day;
1132
1133   g_return_val_if_fail (datetime != NULL, NULL);
1134   g_date_time_get_ymd (datetime, &year, &month, &day);
1135
1136   if (months < -120000 || months > 120000)
1137     return NULL;
1138
1139   year += months / 12;
1140   month += months % 12;
1141   if (month < 1)
1142     {
1143       month += 12;
1144       year--;
1145     }
1146   else if (month > 12)
1147     {
1148       month -= 12;
1149       year++;
1150     }
1151
1152   day = MIN (day, days_in_months[GREGORIAN_LEAP (year)][month]);
1153
1154   return g_date_time_replace_days (datetime, ymd_to_days (year, month, day));
1155 }
1156
1157 /**
1158  * g_date_time_add_weeks:
1159  * @datetime: a #GDateTime
1160  * @weeks: the number of weeks
1161  *
1162  * Creates a copy of @datetime and adds the specified number of weeks to the
1163  * copy.
1164  *
1165  * Return value: the newly created #GDateTime which should be freed with
1166  *   g_date_time_unref().
1167  *
1168  * Since: 2.26
1169  */
1170 GDateTime*
1171 g_date_time_add_weeks (GDateTime *datetime,
1172                        gint             weeks)
1173 {
1174   g_return_val_if_fail (datetime != NULL, NULL);
1175
1176   return g_date_time_add_days (datetime, weeks * 7);
1177 }
1178
1179 /**
1180  * g_date_time_add_days:
1181  * @datetime: a #GDateTime
1182  * @days: the number of days
1183  *
1184  * Creates a copy of @datetime and adds the specified number of days to the
1185  * copy.
1186  *
1187  * Return value: the newly created #GDateTime which should be freed with
1188  *   g_date_time_unref().
1189  *
1190  * Since: 2.26
1191  */
1192 GDateTime*
1193 g_date_time_add_days (GDateTime *datetime,
1194                       gint       days)
1195 {
1196   g_return_val_if_fail (datetime != NULL, NULL);
1197
1198   if (days < -3660000 || days > 3660000)
1199     return NULL;
1200
1201   return g_date_time_replace_days (datetime, datetime->days + days);
1202 }
1203
1204 /**
1205  * g_date_time_add_hours:
1206  * @datetime: a #GDateTime
1207  * @hours: the number of hours to add
1208  *
1209  * Creates a copy of @datetime and adds the specified number of hours
1210  *
1211  * Return value: the newly created #GDateTime which should be freed with
1212  *   g_date_time_unref().
1213  *
1214  * Since: 2.26
1215  */
1216 GDateTime*
1217 g_date_time_add_hours (GDateTime *datetime,
1218                        gint       hours)
1219 {
1220   return g_date_time_add (datetime, hours * USEC_PER_HOUR);
1221 }
1222
1223 /**
1224  * g_date_time_add_minutes:
1225  * @datetime: a #GDateTime
1226  * @minutes: the number of minutes to add
1227  *
1228  * Creates a copy of @datetime adding the specified number of minutes.
1229  *
1230  * Return value: the newly created #GDateTime which should be freed with
1231  *   g_date_time_unref().
1232  *
1233  * Since: 2.26
1234  */
1235 GDateTime*
1236 g_date_time_add_minutes (GDateTime *datetime,
1237                          gint             minutes)
1238 {
1239   return g_date_time_add (datetime, minutes * USEC_PER_MINUTE);
1240 }
1241
1242
1243 /**
1244  * g_date_time_add_seconds:
1245  * @datetime: a #GDateTime
1246  * @seconds: the number of seconds to add
1247  *
1248  * Creates a copy of @datetime and adds the specified number of seconds.
1249  *
1250  * Return value: the newly created #GDateTime which should be freed with
1251  *   g_date_time_unref().
1252  *
1253  * Since: 2.26
1254  */
1255 GDateTime*
1256 g_date_time_add_seconds (GDateTime *datetime,
1257                          gdouble    seconds)
1258 {
1259   return g_date_time_add (datetime, seconds * USEC_PER_SECOND);
1260 }
1261
1262 /**
1263  * g_date_time_add_full:
1264  * @datetime: a #GDateTime
1265  * @years: the number of years to add
1266  * @months: the number of months to add
1267  * @days: the number of days to add
1268  * @hours: the number of hours to add
1269  * @minutes: the number of minutes to add
1270  * @seconds: the number of seconds to add
1271  *
1272  * Creates a new #GDateTime adding the specified values to the current date and
1273  * time in @datetime.
1274  *
1275  * Return value: the newly created #GDateTime that should be freed with
1276  *   g_date_time_unref().
1277  *
1278  * Since: 2.26
1279  */
1280 GDateTime *
1281 g_date_time_add_full (GDateTime *datetime,
1282                       gint       years,
1283                       gint       months,
1284                       gint       days,
1285                       gint       hours,
1286                       gint       minutes,
1287                       gdouble    seconds)
1288 {
1289   gint year, month, day;
1290   gint64 full_time;
1291   GDateTime *new;
1292   gint interval;
1293
1294   g_return_val_if_fail (datetime != NULL, NULL);
1295   g_date_time_get_ymd (datetime, &year, &month, &day);
1296
1297   months += years * 12;
1298
1299   if (months < -120000 || months > 120000)
1300     return NULL;
1301
1302   if (days < -3660000 || days > 3660000)
1303     return NULL;
1304
1305   year += months / 12;
1306   month += months % 12;
1307   if (month < 1)
1308     {
1309       month += 12;
1310       year--;
1311     }
1312   else if (month > 12)
1313     {
1314       month -= 12;
1315       year++;
1316     }
1317
1318   day = MIN (day, days_in_months[GREGORIAN_LEAP (year)][month]);
1319
1320   /* full_time is now in unix (local) time */
1321   full_time = datetime->usec / USEC_PER_SECOND + SEC_PER_DAY *
1322     (ymd_to_days (year, month, day) + days - UNIX_EPOCH_START);
1323
1324   interval = g_time_zone_adjust_time (datetime->tz,
1325                                       g_time_zone_is_dst (datetime->tz,
1326                                                           datetime->interval),
1327                                       &full_time);
1328
1329   /* move to UTC unix time */
1330   full_time -= g_time_zone_get_offset (datetime->tz, interval);
1331
1332   /* convert back to an instant, add back fractional seconds */
1333   full_time += UNIX_EPOCH_START * SEC_PER_DAY;
1334   full_time = full_time * USEC_PER_SECOND +
1335               datetime->usec % USEC_PER_SECOND;
1336
1337   /* do the actual addition now */
1338   full_time += (hours * USEC_PER_HOUR) +
1339                (minutes * USEC_PER_MINUTE) +
1340                (gint64) (seconds * USEC_PER_SECOND);
1341
1342   /* find the new interval */
1343   interval = g_time_zone_find_interval (datetime->tz,
1344                                         G_TIME_TYPE_UNIVERSAL,
1345                                         INSTANT_TO_UNIX (full_time));
1346
1347   /* convert back into local time */
1348   full_time += USEC_PER_SECOND *
1349                g_time_zone_get_offset (datetime->tz, interval);
1350
1351   /* split into days and usec of a new datetime */
1352   new = g_date_time_alloc (datetime->tz);
1353   new->interval = interval;
1354   new->days = full_time / USEC_PER_DAY;
1355   new->usec = full_time % USEC_PER_DAY;
1356
1357   /* XXX validate */
1358
1359   return new;
1360 }
1361
1362 /* Compare, difference, hash, equal {{{1 */
1363 /**
1364  * g_date_time_compare:
1365  * @dt1: first #GDateTime to compare
1366  * @dt2: second #GDateTime to compare
1367  *
1368  * A comparison function for #GDateTimes that is suitable
1369  * as a #GCompareFunc. Both #GDateTimes must be non-%NULL.
1370  *
1371  * Return value: -1, 0 or 1 if @dt1 is less than, equal to or greater
1372  *   than @dt2.
1373  *
1374  * Since: 2.26
1375  */
1376 gint
1377 g_date_time_compare (gconstpointer dt1,
1378                      gconstpointer dt2)
1379 {
1380   gint64 difference;
1381
1382   difference = g_date_time_difference ((GDateTime *) dt1, (GDateTime *) dt2);
1383
1384   if (difference < 0)
1385     return -1;
1386
1387   else if (difference > 0)
1388     return 1;
1389
1390   else
1391     return 0;
1392 }
1393
1394 /**
1395  * g_date_time_difference:
1396  * @end: a #GDateTime
1397  * @begin: a #GDateTime
1398  *
1399  * Calculates the difference in time between @end and @begin.  The
1400  * #GTimeSpan that is returned is effectively @end - @begin (ie:
1401  * positive if the first parameter is larger).
1402  *
1403  * Return value: the difference between the two #GDateTime, as a time
1404  *   span expressed in microseconds.
1405  *
1406  * Since: 2.26
1407  */
1408 GTimeSpan
1409 g_date_time_difference (GDateTime *end,
1410                         GDateTime *begin)
1411 {
1412   g_return_val_if_fail (begin != NULL, 0);
1413   g_return_val_if_fail (end != NULL, 0);
1414
1415   return g_date_time_to_instant (end) -
1416          g_date_time_to_instant (begin);
1417 }
1418
1419 /**
1420  * g_date_time_hash:
1421  * @datetime: a #GDateTime
1422  *
1423  * Hashes @datetime into a #guint, suitable for use within #GHashTable.
1424  *
1425  * Return value: a #guint containing the hash
1426  *
1427  * Since: 2.26
1428  */
1429 guint
1430 g_date_time_hash (gconstpointer datetime)
1431 {
1432   return g_date_time_to_instant ((GDateTime *) datetime);
1433 }
1434
1435 /**
1436  * g_date_time_equal:
1437  * @dt1: a #GDateTime
1438  * @dt2: a #GDateTime
1439  *
1440  * Checks to see if @dt1 and @dt2 are equal.
1441  *
1442  * Equal here means that they represent the same moment after converting
1443  * them to the same time zone.
1444  *
1445  * Return value: %TRUE if @dt1 and @dt2 are equal
1446  *
1447  * Since: 2.26
1448  */
1449 gboolean
1450 g_date_time_equal (gconstpointer dt1,
1451                    gconstpointer dt2)
1452 {
1453   return g_date_time_difference ((GDateTime *) dt1, (GDateTime *) dt2) == 0;
1454 }
1455
1456 /* Year, Month, Day Getters {{{1 */
1457 /**
1458  * g_date_time_get_ymd:
1459  * @datetime: a #GDateTime.
1460  * @year: (out) (allow-none): the return location for the gregorian year, or %NULL.
1461  * @month: (out) (allow-none): the return location for the month of the year, or %NULL.
1462  * @day: (out) (allow-none): the return location for the day of the month, or %NULL.
1463  *
1464  * Retrieves the Gregorian day, month, and year of a given #GDateTime.
1465  *
1466  * Since: 2.26
1467  **/
1468 void
1469 g_date_time_get_ymd (GDateTime *datetime,
1470                      gint      *year,
1471                      gint      *month,
1472                      gint      *day)
1473 {
1474   gint the_year;
1475   gint the_month;
1476   gint the_day;
1477   gint remaining_days;
1478   gint y100_cycles;
1479   gint y4_cycles;
1480   gint y1_cycles;
1481   gint preceding;
1482   gboolean leap;
1483
1484   g_return_if_fail (datetime != NULL);
1485
1486   remaining_days = datetime->days;
1487
1488   /*
1489    * We need to convert an offset in days to its year/month/day representation.
1490    * Leap years makes this a little trickier than it should be, so we use
1491    * 400, 100 and 4 years cycles here to get to the correct year.
1492    */
1493
1494   /* Our days offset starts sets 0001-01-01 as day 1, if it was day 0 our
1495    * math would be simpler, so let's do it */
1496   remaining_days--;
1497
1498   the_year = (remaining_days / DAYS_IN_400YEARS) * 400 + 1;
1499   remaining_days = remaining_days % DAYS_IN_400YEARS;
1500
1501   y100_cycles = remaining_days / DAYS_IN_100YEARS;
1502   remaining_days = remaining_days % DAYS_IN_100YEARS;
1503   the_year += y100_cycles * 100;
1504
1505   y4_cycles = remaining_days / DAYS_IN_4YEARS;
1506   remaining_days = remaining_days % DAYS_IN_4YEARS;
1507   the_year += y4_cycles * 4;
1508
1509   y1_cycles = remaining_days / 365;
1510   the_year += y1_cycles;
1511   remaining_days = remaining_days % 365;
1512
1513   if (y1_cycles == 4 || y100_cycles == 4) {
1514     g_assert (remaining_days == 0);
1515
1516     /* special case that indicates that the date is actually one year before,
1517      * in the 31th of December */
1518     the_year--;
1519     the_month = 12;
1520     the_day = 31;
1521     goto end;
1522   }
1523
1524   /* now get the month and the day */
1525   leap = y1_cycles == 3 && (y4_cycles != 24 || y100_cycles == 3);
1526
1527   g_assert (leap == GREGORIAN_LEAP(the_year));
1528
1529   the_month = (remaining_days + 50) >> 5;
1530   preceding = (days_in_year[0][the_month - 1] + (the_month > 2 && leap));
1531   if (preceding > remaining_days)
1532     {
1533       /* estimate is too large */
1534       the_month -= 1;
1535       preceding -= leap ? days_in_months[1][the_month]
1536                         : days_in_months[0][the_month];
1537     }
1538
1539   remaining_days -= preceding;
1540   g_assert(0 <= remaining_days);
1541
1542   the_day = remaining_days + 1;
1543
1544 end:
1545   if (year)
1546     *year = the_year;
1547   if (month)
1548     *month = the_month;
1549   if (day)
1550     *day = the_day;
1551 }
1552
1553 /**
1554  * g_date_time_get_year:
1555  * @datetime: A #GDateTime
1556  *
1557  * Retrieves the year represented by @datetime in the Gregorian calendar.
1558  *
1559  * Return value: the year represented by @datetime
1560  *
1561  * Since: 2.26
1562  */
1563 gint
1564 g_date_time_get_year (GDateTime *datetime)
1565 {
1566   gint year;
1567
1568   g_return_val_if_fail (datetime != NULL, 0);
1569
1570   g_date_time_get_ymd (datetime, &year, NULL, NULL);
1571
1572   return year;
1573 }
1574
1575 /**
1576  * g_date_time_get_month:
1577  * @datetime: a #GDateTime
1578  *
1579  * Retrieves the month of the year represented by @datetime in the Gregorian
1580  * calendar.
1581  *
1582  * Return value: the month represented by @datetime
1583  *
1584  * Since: 2.26
1585  */
1586 gint
1587 g_date_time_get_month (GDateTime *datetime)
1588 {
1589   gint month;
1590
1591   g_return_val_if_fail (datetime != NULL, 0);
1592
1593   g_date_time_get_ymd (datetime, NULL, &month, NULL);
1594
1595   return month;
1596 }
1597
1598 /**
1599  * g_date_time_get_day_of_month:
1600  * @datetime: a #GDateTime
1601  *
1602  * Retrieves the day of the month represented by @datetime in the gregorian
1603  * calendar.
1604  *
1605  * Return value: the day of the month
1606  *
1607  * Since: 2.26
1608  */
1609 gint
1610 g_date_time_get_day_of_month (GDateTime *datetime)
1611 {
1612   gint           day_of_year,
1613                  i;
1614   const guint16 *days;
1615   guint16        last = 0;
1616
1617   g_return_val_if_fail (datetime != NULL, 0);
1618
1619   days = days_in_year[GREGORIAN_LEAP (g_date_time_get_year (datetime)) ? 1 : 0];
1620   g_date_time_get_week_number (datetime, NULL, NULL, &day_of_year);
1621
1622   for (i = 1; i <= 12; i++)
1623     {
1624       if (days [i] >= day_of_year)
1625         return day_of_year - last;
1626       last = days [i];
1627     }
1628
1629   g_warn_if_reached ();
1630   return 0;
1631 }
1632
1633 /* Week of year / day of week getters {{{1 */
1634 /**
1635  * g_date_time_get_week_numbering_year:
1636  * @datetime: a #GDateTime
1637  *
1638  * Returns the ISO 8601 week-numbering year in which the week containing
1639  * @datetime falls.
1640  *
1641  * This function, taken together with g_date_time_get_week_of_year() and
1642  * g_date_time_get_day_of_week() can be used to determine the full ISO
1643  * week date on which @datetime falls.
1644  *
1645  * This is usually equal to the normal Gregorian year (as returned by
1646  * g_date_time_get_year()), except as detailed below:
1647  *
1648  * For Thursday, the week-numbering year is always equal to the usual
1649  * calendar year.  For other days, the number is such that every day
1650  * within a complete week (Monday to Sunday) is contained within the
1651  * same week-numbering year.
1652  *
1653  * For Monday, Tuesday and Wednesday occurring near the end of the year,
1654  * this may mean that the week-numbering year is one greater than the
1655  * calendar year (so that these days have the same week-numbering year
1656  * as the Thursday occurring early in the next year).
1657  *
1658  * For Friday, Saturaday and Sunday occurring near the start of the year,
1659  * this may mean that the week-numbering year is one less than the
1660  * calendar year (so that these days have the same week-numbering year
1661  * as the Thursday occurring late in the previous year).
1662  *
1663  * An equivalent description is that the week-numbering year is equal to
1664  * the calendar year containing the majority of the days in the current
1665  * week (Monday to Sunday).
1666  *
1667  * Note that January 1 0001 in the proleptic Gregorian calendar is a
1668  * Monday, so this function never returns 0.
1669  *
1670  * Returns: the ISO 8601 week-numbering year for @datetime
1671  *
1672  * Since: 2.26
1673  **/
1674 gint
1675 g_date_time_get_week_numbering_year (GDateTime *datetime)
1676 {
1677   gint year, month, day, weekday;
1678
1679   g_date_time_get_ymd (datetime, &year, &month, &day);
1680   weekday = g_date_time_get_day_of_week (datetime);
1681
1682   /* January 1, 2, 3 might be in the previous year if they occur after
1683    * Thursday.
1684    *
1685    *   Jan 1:  Friday, Saturday, Sunday    =>  day 1:  weekday 5, 6, 7
1686    *   Jan 2:  Saturday, Sunday            =>  day 2:  weekday 6, 7
1687    *   Jan 3:  Sunday                      =>  day 3:  weekday 7
1688    *
1689    * So we have a special case if (day - weekday) <= -4
1690    */
1691   if (month == 1 && (day - weekday) <= -4)
1692     return year - 1;
1693
1694   /* December 29, 30, 31 might be in the next year if they occur before
1695    * Thursday.
1696    *
1697    *   Dec 31: Monday, Tuesday, Wednesday  =>  day 31: weekday 1, 2, 3
1698    *   Dec 30: Monday, Tuesday             =>  day 30: weekday 1, 2
1699    *   Dec 29: Monday                      =>  day 29: weekday 1
1700    *
1701    * So we have a special case if (day - weekday) >= 28
1702    */
1703   else if (month == 12 && (day - weekday) >= 28)
1704     return year + 1;
1705
1706   else
1707     return year;
1708 }
1709
1710 /**
1711  * g_date_time_get_week_of_year:
1712  * @datetime: a #GDateTime
1713  *
1714  * Returns the ISO 8601 week number for the week containing @datetime.
1715  * The ISO 8601 week number is the same for every day of the week (from
1716  * Moday through Sunday).  That can produce some unusual results
1717  * (described below).
1718  *
1719  * The first week of the year is week 1.  This is the week that contains
1720  * the first Thursday of the year.  Equivalently, this is the first week
1721  * that has more than 4 of its days falling within the calendar year.
1722  *
1723  * The value 0 is never returned by this function.  Days contained
1724  * within a year but occurring before the first ISO 8601 week of that
1725  * year are considered as being contained in the last week of the
1726  * previous year.  Similarly, the final days of a calendar year may be
1727  * considered as being part of the first ISO 8601 week of the next year
1728  * if 4 or more days of that week are contained within the new year.
1729  *
1730  * Returns: the ISO 8601 week number for @datetime.
1731  *
1732  * Since: 2.26
1733  */
1734 gint
1735 g_date_time_get_week_of_year (GDateTime *datetime)
1736 {
1737   gint weeknum;
1738
1739   g_return_val_if_fail (datetime != NULL, 0);
1740
1741   g_date_time_get_week_number (datetime, &weeknum, NULL, NULL);
1742
1743   return weeknum;
1744 }
1745
1746 /**
1747  * g_date_time_get_day_of_week:
1748  * @datetime: a #GDateTime
1749  *
1750  * Retrieves the ISO 8601 day of the week on which @datetime falls (1 is
1751  * Monday, 2 is Tuesday... 7 is Sunday).
1752  *
1753  * Return value: the day of the week
1754  *
1755  * Since: 2.26
1756  */
1757 gint
1758 g_date_time_get_day_of_week (GDateTime *datetime)
1759 {
1760   g_return_val_if_fail (datetime != NULL, 0);
1761
1762   return (datetime->days - 1) % 7 + 1;
1763 }
1764
1765 /* Day of year getter {{{1 */
1766 /**
1767  * g_date_time_get_day_of_year:
1768  * @datetime: a #GDateTime
1769  *
1770  * Retrieves the day of the year represented by @datetime in the Gregorian
1771  * calendar.
1772  *
1773  * Return value: the day of the year
1774  *
1775  * Since: 2.26
1776  */
1777 gint
1778 g_date_time_get_day_of_year (GDateTime *datetime)
1779 {
1780   gint doy = 0;
1781
1782   g_return_val_if_fail (datetime != NULL, 0);
1783
1784   g_date_time_get_week_number (datetime, NULL, NULL, &doy);
1785   return doy;
1786 }
1787
1788 /* Time component getters {{{1 */
1789
1790 /**
1791  * g_date_time_get_hour:
1792  * @datetime: a #GDateTime
1793  *
1794  * Retrieves the hour of the day represented by @datetime
1795  *
1796  * Return value: the hour of the day
1797  *
1798  * Since: 2.26
1799  */
1800 gint
1801 g_date_time_get_hour (GDateTime *datetime)
1802 {
1803   g_return_val_if_fail (datetime != NULL, 0);
1804
1805   return (datetime->usec / USEC_PER_HOUR);
1806 }
1807
1808 /**
1809  * g_date_time_get_minute:
1810  * @datetime: a #GDateTime
1811  *
1812  * Retrieves the minute of the hour represented by @datetime
1813  *
1814  * Return value: the minute of the hour
1815  *
1816  * Since: 2.26
1817  */
1818 gint
1819 g_date_time_get_minute (GDateTime *datetime)
1820 {
1821   g_return_val_if_fail (datetime != NULL, 0);
1822
1823   return (datetime->usec % USEC_PER_HOUR) / USEC_PER_MINUTE;
1824 }
1825
1826 /**
1827  * g_date_time_get_second:
1828  * @datetime: a #GDateTime
1829  *
1830  * Retrieves the second of the minute represented by @datetime
1831  *
1832  * Return value: the second represented by @datetime
1833  *
1834  * Since: 2.26
1835  */
1836 gint
1837 g_date_time_get_second (GDateTime *datetime)
1838 {
1839   g_return_val_if_fail (datetime != NULL, 0);
1840
1841   return (datetime->usec % USEC_PER_MINUTE) / USEC_PER_SECOND;
1842 }
1843
1844 /**
1845  * g_date_time_get_microsecond:
1846  * @datetime: a #GDateTime
1847  *
1848  * Retrieves the microsecond of the date represented by @datetime
1849  *
1850  * Return value: the microsecond of the second
1851  *
1852  * Since: 2.26
1853  */
1854 gint
1855 g_date_time_get_microsecond (GDateTime *datetime)
1856 {
1857   g_return_val_if_fail (datetime != NULL, 0);
1858
1859   return (datetime->usec % USEC_PER_SECOND);
1860 }
1861
1862 /**
1863  * g_date_time_get_seconds:
1864  * @datetime: a #GDateTime
1865  *
1866  * Retrieves the number of seconds since the start of the last minute,
1867  * including the fractional part.
1868  *
1869  * Returns: the number of seconds
1870  *
1871  * Since: 2.26
1872  **/
1873 gdouble
1874 g_date_time_get_seconds (GDateTime *datetime)
1875 {
1876   g_return_val_if_fail (datetime != NULL, 0);
1877
1878   return (datetime->usec % USEC_PER_MINUTE) / 1000000.0;
1879 }
1880
1881 /* Exporters {{{1 */
1882 /**
1883  * g_date_time_to_unix:
1884  * @datetime: a #GDateTime
1885  *
1886  * Gives the Unix time corresponding to @datetime, rounding down to the
1887  * nearest second.
1888  *
1889  * Unix time is the number of seconds that have elapsed since 1970-01-01
1890  * 00:00:00 UTC, regardless of the time zone associated with @datetime.
1891  *
1892  * Returns: the Unix time corresponding to @datetime
1893  *
1894  * Since: 2.26
1895  **/
1896 gint64
1897 g_date_time_to_unix (GDateTime *datetime)
1898 {
1899   return INSTANT_TO_UNIX (g_date_time_to_instant (datetime));
1900 }
1901
1902 /**
1903  * g_date_time_to_timeval:
1904  * @datetime: a #GDateTime
1905  * @tv: a #GTimeVal to modify
1906  *
1907  * Stores the instant in time that @datetime represents into @tv.
1908  *
1909  * The time contained in a #GTimeVal is always stored in the form of
1910  * seconds elapsed since 1970-01-01 00:00:00 UTC, regardless of the time
1911  * zone associated with @datetime.
1912  *
1913  * On systems where 'long' is 32bit (ie: all 32bit systems and all
1914  * Windows systems), a #GTimeVal is incapable of storing the entire
1915  * range of values that #GDateTime is capable of expressing.  On those
1916  * systems, this function returns %FALSE to indicate that the time is
1917  * out of range.
1918  *
1919  * On systems where 'long' is 64bit, this function never fails.
1920  *
1921  * Returns: %TRUE if successful, else %FALSE
1922  *
1923  * Since: 2.26
1924  **/
1925 gboolean
1926 g_date_time_to_timeval (GDateTime *datetime,
1927                         GTimeVal  *tv)
1928 {
1929   tv->tv_sec = INSTANT_TO_UNIX (g_date_time_to_instant (datetime));
1930   tv->tv_usec = datetime->usec % USEC_PER_SECOND;
1931
1932   return TRUE;
1933 }
1934
1935 /* Timezone queries {{{1 */
1936 /**
1937  * g_date_time_get_utc_offset:
1938  * @datetime: a #GDateTime
1939  *
1940  * Determines the offset to UTC in effect at the time and in the time
1941  * zone of @datetime.
1942  *
1943  * The offset is the number of microseconds that you add to UTC time to
1944  * arrive at local time for the time zone (ie: negative numbers for time
1945  * zones west of GMT, positive numbers for east).
1946  *
1947  * If @datetime represents UTC time, then the offset is always zero.
1948  *
1949  * Returns: the number of microseconds that should be added to UTC to
1950  *          get the local time
1951  *
1952  * Since: 2.26
1953  **/
1954 GTimeSpan
1955 g_date_time_get_utc_offset (GDateTime *datetime)
1956 {
1957   gint offset;
1958
1959   g_return_val_if_fail (datetime != NULL, 0);
1960
1961   offset = g_time_zone_get_offset (datetime->tz, datetime->interval);
1962
1963   return (gint64) offset * USEC_PER_SECOND;
1964 }
1965
1966 /**
1967  * g_date_time_get_timezone_abbreviation:
1968  * @datetime: a #GDateTime
1969  *
1970  * Determines the time zone abbreviation to be used at the time and in
1971  * the time zone of @datetime.
1972  *
1973  * For example, in Toronto this is currently "EST" during the winter
1974  * months and "EDT" during the summer months when daylight savings
1975  * time is in effect.
1976  *
1977  * Returns: (transfer none): the time zone abbreviation. The returned
1978  *          string is owned by the #GDateTime and it should not be
1979  *          modified or freed
1980  *
1981  * Since: 2.26
1982  **/
1983 const gchar *
1984 g_date_time_get_timezone_abbreviation (GDateTime *datetime)
1985 {
1986   g_return_val_if_fail (datetime != NULL, NULL);
1987
1988   return g_time_zone_get_abbreviation (datetime->tz, datetime->interval);
1989 }
1990
1991 /**
1992  * g_date_time_is_daylight_savings:
1993  * @datetime: a #GDateTime
1994  *
1995  * Determines if daylight savings time is in effect at the time and in
1996  * the time zone of @datetime.
1997  *
1998  * Returns: %TRUE if daylight savings time is in effect
1999  *
2000  * Since: 2.26
2001  **/
2002 gboolean
2003 g_date_time_is_daylight_savings (GDateTime *datetime)
2004 {
2005   g_return_val_if_fail (datetime != NULL, FALSE);
2006
2007   return g_time_zone_is_dst (datetime->tz, datetime->interval);
2008 }
2009
2010 /* Timezone convert {{{1 */
2011 /**
2012  * g_date_time_to_timezone:
2013  * @datetime: a #GDateTime
2014  * @tz: the new #GTimeZone
2015  *
2016  * Create a new #GDateTime corresponding to the same instant in time as
2017  * @datetime, but in the time zone @tz.
2018  *
2019  * This call can fail in the case that the time goes out of bounds.  For
2020  * example, converting 0001-01-01 00:00:00 UTC to a time zone west of
2021  * Greenwich will fail (due to the year 0 being out of range).
2022  *
2023  * You should release the return value by calling g_date_time_unref()
2024  * when you are done with it.
2025  *
2026  * Returns: a new #GDateTime, or %NULL
2027  *
2028  * Since: 2.26
2029  **/
2030 GDateTime *
2031 g_date_time_to_timezone (GDateTime *datetime,
2032                          GTimeZone *tz)
2033 {
2034   return g_date_time_from_instant (tz, g_date_time_to_instant (datetime));
2035 }
2036
2037 /**
2038  * g_date_time_to_local:
2039  * @datetime: a #GDateTime
2040  *
2041  * Creates a new #GDateTime corresponding to the same instant in time as
2042  * @datetime, but in the local time zone.
2043  *
2044  * This call is equivalent to calling g_date_time_to_timezone() with the
2045  * time zone returned by g_time_zone_new_local().
2046  *
2047  * Returns: the newly created #GDateTime
2048  *
2049  * Since: 2.26
2050  **/
2051 GDateTime *
2052 g_date_time_to_local (GDateTime *datetime)
2053 {
2054   GDateTime *new;
2055   GTimeZone *local;
2056
2057   local = g_time_zone_new_local ();
2058   new = g_date_time_to_timezone (datetime, local);
2059   g_time_zone_unref (local);
2060
2061   return new;
2062 }
2063
2064 /**
2065  * g_date_time_to_utc:
2066  * @datetime: a #GDateTime
2067  *
2068  * Creates a new #GDateTime corresponding to the same instant in time as
2069  * @datetime, but in UTC.
2070  *
2071  * This call is equivalent to calling g_date_time_to_timezone() with the
2072  * time zone returned by g_time_zone_new_utc().
2073  *
2074  * Returns: the newly created #GDateTime
2075  *
2076  * Since: 2.26
2077  **/
2078 GDateTime *
2079 g_date_time_to_utc (GDateTime *datetime)
2080 {
2081   GDateTime *new;
2082   GTimeZone *utc;
2083
2084   utc = g_time_zone_new_utc ();
2085   new = g_date_time_to_timezone (datetime, utc);
2086   g_time_zone_unref (utc);
2087
2088   return new;
2089 }
2090
2091 /* Format {{{1 */
2092
2093 static void
2094 format_number (GString  *str,
2095                gboolean  use_alt_digits,
2096                gchar    *pad,
2097                gint      width,
2098                guint32   number)
2099 {
2100   const gchar *ascii_digits[10] = {
2101     "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
2102   };
2103   const gchar **digits = ascii_digits;
2104   const gchar *tmp[10];
2105   gint i = 0;
2106
2107   g_return_if_fail (width <= 10);
2108
2109 #ifdef HAVE_LANGINFO_OUTDIGIT
2110   if (use_alt_digits)
2111     {
2112       static const gchar *alt_digits[10];
2113       static gsize initialised;
2114       /* 2^32 has 10 digits */
2115
2116       if G_UNLIKELY (g_once_init_enter (&initialised))
2117         {
2118 #define DO_DIGIT(n) \
2119         alt_digits[n] = nl_langinfo (_NL_CTYPE_OUTDIGIT## n ##_MB)
2120           DO_DIGIT(0); DO_DIGIT(1); DO_DIGIT(2); DO_DIGIT(3); DO_DIGIT(4);
2121           DO_DIGIT(5); DO_DIGIT(6); DO_DIGIT(7); DO_DIGIT(8); DO_DIGIT(9);
2122 #undef DO_DIGIT
2123           g_once_init_leave (&initialised, TRUE);
2124         }
2125
2126       digits = alt_digits;
2127     }
2128 #endif /* HAVE_LANGINFO_OUTDIGIT */
2129
2130   do
2131     {
2132       tmp[i++] = digits[number % 10];
2133       number /= 10;
2134     }
2135   while (number);
2136
2137   while (pad && i < width)
2138     tmp[i++] = *pad == '0' ? digits[0] : pad;
2139
2140   /* should really be impossible */
2141   g_assert (i <= 10);
2142
2143   while (i)
2144     g_string_append (str, tmp[--i]);
2145 }
2146
2147 static gboolean g_date_time_format_locale (GDateTime   *datetime,
2148                                            const gchar *format,
2149                                            GString     *outstr,
2150                                            gboolean     locale_is_utf8);
2151
2152 /* g_date_time_format() subroutine that takes a locale-encoded format
2153  * string and produces a locale-encoded date/time string.
2154  */
2155 static gboolean
2156 g_date_time_locale_format_locale (GDateTime   *datetime,
2157                                   const gchar *format,
2158                                   GString     *outstr,
2159                                   gboolean     locale_is_utf8)
2160 {
2161   gchar *utf8_format;
2162   gboolean success;
2163
2164   if (locale_is_utf8)
2165     return g_date_time_format_locale (datetime, format, outstr,
2166                                       locale_is_utf8);
2167
2168   utf8_format = g_locale_to_utf8 (format, -1, NULL, NULL, NULL);
2169   if (!utf8_format)
2170     return FALSE;
2171
2172   success = g_date_time_format_locale (datetime, utf8_format, outstr,
2173                                        locale_is_utf8);
2174   g_free (utf8_format);
2175   return success;
2176 }
2177
2178 /* g_date_time_format() subroutine that takes a UTF-8 format
2179  * string and produces a locale-encoded date/time string.
2180  */
2181 static gboolean
2182 g_date_time_format_locale (GDateTime   *datetime,
2183                            const gchar *format,
2184                            GString     *outstr,
2185                            gboolean     locale_is_utf8)
2186 {
2187   guint     len;
2188   gchar    *tmp;
2189   gunichar  c;
2190   gboolean  alt_digits = FALSE;
2191   gboolean  pad_set = FALSE;
2192   gchar    *pad = "";
2193   gchar    *ampm;
2194   const gchar *tz;
2195
2196   while (*format)
2197     {
2198       len = strcspn (format, "%");
2199       if (len)
2200         {
2201           if (locale_is_utf8)
2202             g_string_append_len (outstr, format, len);
2203           else
2204             {
2205               tmp = g_locale_from_utf8 (format, len, NULL, NULL, NULL);
2206               if (!tmp)
2207                 return FALSE;
2208               g_string_append (outstr, tmp);
2209               g_free (tmp);
2210             }
2211         }
2212
2213       format += len;
2214       if (!*format)
2215         break;
2216
2217       g_assert (*format == '%');
2218       format++;
2219       if (!*format)
2220         break;
2221
2222       alt_digits = FALSE;
2223       pad_set = FALSE;
2224
2225     next_mod:
2226       c = g_utf8_get_char (format);
2227       format = g_utf8_next_char (format);
2228       switch (c)
2229         {
2230         case 'a':
2231           g_string_append (outstr, WEEKDAY_ABBR (datetime));
2232           break;
2233         case 'A':
2234           g_string_append (outstr, WEEKDAY_FULL (datetime));
2235           break;
2236         case 'b':
2237           g_string_append (outstr, MONTH_ABBR (datetime));
2238           break;
2239         case 'B':
2240           g_string_append (outstr, MONTH_FULL (datetime));
2241           break;
2242         case 'c':
2243           {
2244             if (!g_date_time_locale_format_locale (datetime, PREFERRED_DATE_TIME_FMT,
2245                                                    outstr, locale_is_utf8))
2246               return FALSE;
2247           }
2248           break;
2249         case 'C':
2250           format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
2251                          g_date_time_get_year (datetime) / 100);
2252           break;
2253         case 'd':
2254           format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
2255                          g_date_time_get_day_of_month (datetime));
2256           break;
2257         case 'e':
2258           format_number (outstr, alt_digits, pad_set ? pad : " ", 2,
2259                          g_date_time_get_day_of_month (datetime));
2260           break;
2261         case 'F':
2262           g_string_append_printf (outstr, "%d-%02d-%02d",
2263                                   g_date_time_get_year (datetime),
2264                                   g_date_time_get_month (datetime),
2265                                   g_date_time_get_day_of_month (datetime));
2266           break;
2267         case 'g':
2268           format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
2269                          g_date_time_get_week_numbering_year (datetime) % 100);
2270           break;
2271         case 'G':
2272           format_number (outstr, alt_digits, pad_set ? pad : 0, 0,
2273                          g_date_time_get_week_numbering_year (datetime));
2274           break;
2275         case 'h':
2276           g_string_append (outstr, MONTH_ABBR (datetime));
2277           break;
2278         case 'H':
2279           format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
2280                          g_date_time_get_hour (datetime));
2281           break;
2282         case 'I':
2283           format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
2284                          (g_date_time_get_hour (datetime) + 11) % 12 + 1);
2285           break;
2286         case 'j':
2287           format_number (outstr, alt_digits, pad_set ? pad : "0", 3,
2288                          g_date_time_get_day_of_year (datetime));
2289           break;
2290         case 'k':
2291           format_number (outstr, alt_digits, pad_set ? pad : " ", 2,
2292                          g_date_time_get_hour (datetime));
2293           break;
2294         case 'l':
2295           format_number (outstr, alt_digits, pad_set ? pad : " ", 2,
2296                          (g_date_time_get_hour (datetime) + 11) % 12 + 1);
2297           break;
2298         case 'n':
2299           g_string_append_c (outstr, '\n');
2300           break;
2301         case 'm':
2302           format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
2303                          g_date_time_get_month (datetime));
2304           break;
2305         case 'M':
2306           format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
2307                          g_date_time_get_minute (datetime));
2308           break;
2309         case 'O':
2310           alt_digits = TRUE;
2311           goto next_mod;
2312         case 'p':
2313           ampm = (gchar *) GET_AMPM (datetime);
2314           if (!locale_is_utf8)
2315             {
2316               ampm = tmp = g_locale_to_utf8 (ampm, -1, NULL, NULL, NULL);
2317               if (!tmp)
2318                 return FALSE;
2319             }
2320           ampm = g_utf8_strup (ampm, -1);
2321           if (!locale_is_utf8)
2322             {
2323               g_free (tmp);
2324               tmp = g_locale_from_utf8 (ampm, -1, NULL, NULL, NULL);
2325               g_free (ampm);
2326               if (!tmp)
2327                 return FALSE;
2328               ampm = tmp;
2329             }
2330           g_string_append (outstr, ampm);
2331           g_free (ampm);
2332           break;
2333         case 'P':
2334           ampm = (gchar *) GET_AMPM (datetime);
2335           if (!locale_is_utf8)
2336             {
2337               ampm = tmp = g_locale_to_utf8 (ampm, -1, NULL, NULL, NULL);
2338               if (!tmp)
2339                 return FALSE;
2340             }
2341           ampm = g_utf8_strdown (ampm, -1);
2342           if (!locale_is_utf8)
2343             {
2344               g_free (tmp);
2345               tmp = g_locale_from_utf8 (ampm, -1, NULL, NULL, NULL);
2346               g_free (ampm);
2347               if (!tmp)
2348                 return FALSE;
2349               ampm = tmp;
2350             }
2351           g_string_append (outstr, ampm);
2352           g_free (ampm);
2353           break;
2354         case 'r':
2355           {
2356             if (!g_date_time_locale_format_locale (datetime, PREFERRED_12HR_TIME_FMT,
2357                                                    outstr, locale_is_utf8))
2358               return FALSE;
2359           }
2360           break;
2361         case 'R':
2362           g_string_append_printf (outstr, "%02d:%02d",
2363                                   g_date_time_get_hour (datetime),
2364                                   g_date_time_get_minute (datetime));
2365           break;
2366         case 's':
2367           g_string_append_printf (outstr, "%" G_GINT64_FORMAT, g_date_time_to_unix (datetime));
2368           break;
2369         case 'S':
2370           format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
2371                          g_date_time_get_second (datetime));
2372           break;
2373         case 't':
2374           g_string_append_c (outstr, '\t');
2375           break;
2376         case 'T':
2377           g_string_append_printf (outstr, "%02d:%02d:%02d",
2378                                   g_date_time_get_hour (datetime),
2379                                   g_date_time_get_minute (datetime),
2380                                   g_date_time_get_second (datetime));
2381           break;
2382         case 'u':
2383           format_number (outstr, alt_digits, 0, 0,
2384                          g_date_time_get_day_of_week (datetime));
2385           break;
2386         case 'V':
2387           format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
2388                          g_date_time_get_week_of_year (datetime));
2389           break;
2390         case 'w':
2391           format_number (outstr, alt_digits, 0, 0,
2392                          g_date_time_get_day_of_week (datetime) % 7);
2393           break;
2394         case 'x':
2395           {
2396             if (!g_date_time_locale_format_locale (datetime, PREFERRED_DATE_FMT,
2397                                                    outstr, locale_is_utf8))
2398               return FALSE;
2399           }
2400           break;
2401         case 'X':
2402           {
2403             if (!g_date_time_locale_format_locale (datetime, PREFERRED_TIME_FMT,
2404                                                    outstr, locale_is_utf8))
2405               return FALSE;
2406           }
2407           break;
2408         case 'y':
2409           format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
2410                          g_date_time_get_year (datetime) % 100);
2411           break;
2412         case 'Y':
2413           format_number (outstr, alt_digits, 0, 0,
2414                          g_date_time_get_year (datetime));
2415           break;
2416         case 'z':
2417           if (datetime->tz != NULL)
2418             {
2419               gint64 offset = g_date_time_get_utc_offset (datetime)
2420                 / USEC_PER_SECOND;
2421
2422               g_string_append_printf (outstr, "%+03d%02d",
2423                                       (int) offset / 3600,
2424                                       (int) abs(offset) / 60 % 60);
2425             }
2426           else
2427             g_string_append (outstr, "+0000");
2428           break;
2429         case 'Z':
2430           tz = g_date_time_get_timezone_abbreviation (datetime);
2431           if (!locale_is_utf8)
2432             {
2433               tz = tmp = g_locale_from_utf8 (tz, -1, NULL, NULL, NULL);
2434               if (!tmp)
2435                 return FALSE;
2436             }
2437           g_string_append (outstr, tz);
2438           if (!locale_is_utf8)
2439             g_free (tmp);
2440           break;
2441         case '%':
2442           g_string_append_c (outstr, '%');
2443           break;
2444         case '-':
2445           pad_set = TRUE;
2446           pad = "";
2447           goto next_mod;
2448         case '_':
2449           pad_set = TRUE;
2450           pad = " ";
2451           goto next_mod;
2452         case '0':
2453           pad_set = TRUE;
2454           pad = "0";
2455           goto next_mod;
2456         default:
2457           return FALSE;
2458         }
2459     }
2460
2461   return TRUE;
2462 }
2463
2464 /**
2465  * g_date_time_format:
2466  * @datetime: A #GDateTime
2467  * @format: a valid UTF-8 string, containing the format for the
2468  *          #GDateTime
2469  *
2470  * Creates a newly allocated string representing the requested @format.
2471  *
2472  * The format strings understood by this function are a subset of the
2473  * strftime() format language as specified by C99.  The \%D, \%U and \%W
2474  * conversions are not supported, nor is the 'E' modifier.  The GNU
2475  * extensions \%k, \%l, \%s and \%P are supported, however, as are the
2476  * '0', '_' and '-' modifiers.
2477  *
2478  * In contrast to strftime(), this function always produces a UTF-8
2479  * string, regardless of the current locale.  Note that the rendering of
2480  * many formats is locale-dependent and may not match the strftime()
2481  * output exactly.
2482  *
2483  * The following format specifiers are supported:
2484  *
2485  * <variablelist>
2486  *  <varlistentry><term>
2487  *    <literal>\%a</literal>:
2488  *   </term><listitem><simpara>
2489  *    the abbreviated weekday name according to the current locale
2490  *  </simpara></listitem></varlistentry>
2491  *  <varlistentry><term>
2492  *    <literal>\%A</literal>:
2493  *   </term><listitem><simpara>
2494  *    the full weekday name according to the current locale
2495  *  </simpara></listitem></varlistentry>
2496  *  <varlistentry><term>
2497  *    <literal>\%b</literal>:
2498  *   </term><listitem><simpara>
2499  *    the abbreviated month name according to the current locale
2500  *  </simpara></listitem></varlistentry>
2501  *  <varlistentry><term>
2502  *    <literal>\%B</literal>:
2503  *   </term><listitem><simpara>
2504  *    the full month name according to the current locale
2505  *  </simpara></listitem></varlistentry>
2506  *  <varlistentry><term>
2507  *    <literal>\%c</literal>:
2508  *   </term><listitem><simpara>
2509  *    the  preferred  date  and  time  representation  for the current locale
2510  *  </simpara></listitem></varlistentry>
2511  *  <varlistentry><term>
2512  *    <literal>\%C</literal>:
2513  *   </term><listitem><simpara>
2514  *    The century number (year/100) as a 2-digit integer (00-99)
2515  *  </simpara></listitem></varlistentry>
2516  *  <varlistentry><term>
2517  *    <literal>\%d</literal>:
2518  *   </term><listitem><simpara>
2519  *    the day of the month as a decimal number (range 01 to 31)
2520  *  </simpara></listitem></varlistentry>
2521  *  <varlistentry><term>
2522  *    <literal>\%e</literal>:
2523  *   </term><listitem><simpara>
2524  *    the day of the month as a decimal number (range  1 to 31)
2525  *  </simpara></listitem></varlistentry>
2526  *  <varlistentry><term>
2527  *    <literal>\%F</literal>:
2528  *   </term><listitem><simpara>
2529  *    equivalent to <literal>\%Y-\%m-\%d</literal> (the ISO 8601 date
2530  *    format)
2531  *  </simpara></listitem></varlistentry>
2532  *  <varlistentry><term>
2533  *    <literal>\%g</literal>:
2534  *   </term><listitem><simpara>
2535  *    the last two digits of the ISO 8601 week-based year as a decimal
2536  *    number (00-99).  This works well with \%V and \%u.
2537  *  </simpara></listitem></varlistentry>
2538  *  <varlistentry><term>
2539  *    <literal>\%G</literal>:
2540  *   </term><listitem><simpara>
2541  *    the ISO 8601 week-based year as a decimal number.  This works well
2542  *    with \%V and \%u.
2543  *  </simpara></listitem></varlistentry>
2544  *  <varlistentry><term>
2545  *    <literal>\%h</literal>:
2546  *   </term><listitem><simpara>
2547  *    equivalent to <literal>\%b</literal>
2548  *  </simpara></listitem></varlistentry>
2549  *  <varlistentry><term>
2550  *    <literal>\%H</literal>:
2551  *   </term><listitem><simpara>
2552  *    the hour as a decimal number using a 24-hour clock (range 00 to
2553  *    23)
2554  *  </simpara></listitem></varlistentry>
2555  *  <varlistentry><term>
2556  *    <literal>\%I</literal>:
2557  *   </term><listitem><simpara>
2558  *    the hour as a decimal number using a 12-hour clock (range 01 to
2559  *    12)
2560  *  </simpara></listitem></varlistentry>
2561  *  <varlistentry><term>
2562  *    <literal>\%j</literal>:
2563  *   </term><listitem><simpara>
2564  *    the day of the year as a decimal number (range 001 to 366)
2565  *  </simpara></listitem></varlistentry>
2566  *  <varlistentry><term>
2567  *    <literal>\%k</literal>:
2568  *   </term><listitem><simpara>
2569  *    the hour (24-hour clock) as a decimal number (range 0 to 23);
2570  *    single digits are preceded by a blank
2571  *  </simpara></listitem></varlistentry>
2572  *  <varlistentry><term>
2573  *    <literal>\%l</literal>:
2574  *   </term><listitem><simpara>
2575  *    the hour (12-hour clock) as a decimal number (range 1 to 12);
2576  *    single digits are preceded by a blank
2577  *  </simpara></listitem></varlistentry>
2578  *  <varlistentry><term>
2579  *    <literal>\%m</literal>:
2580  *   </term><listitem><simpara>
2581  *    the month as a decimal number (range 01 to 12)
2582  *  </simpara></listitem></varlistentry>
2583  *  <varlistentry><term>
2584  *    <literal>\%M</literal>:
2585  *   </term><listitem><simpara>
2586  *    the minute as a decimal number (range 00 to 59)
2587  *  </simpara></listitem></varlistentry>
2588  *  <varlistentry><term>
2589  *    <literal>\%p</literal>:
2590  *   </term><listitem><simpara>
2591  *    either "AM" or "PM" according to the given time value, or the
2592  *    corresponding  strings for the current locale.  Noon is treated as
2593  *    "PM" and midnight as "AM".
2594  *  </simpara></listitem></varlistentry>
2595  *  <varlistentry><term>
2596  *    <literal>\%P</literal>:
2597  *   </term><listitem><simpara>
2598  *    like \%p but lowercase: "am" or "pm" or a corresponding string for
2599  *    the current locale
2600  *  </simpara></listitem></varlistentry>
2601  *  <varlistentry><term>
2602  *    <literal>\%r</literal>:
2603  *   </term><listitem><simpara>
2604  *    the time in a.m. or p.m. notation
2605  *  </simpara></listitem></varlistentry>
2606  *  <varlistentry><term>
2607  *    <literal>\%R</literal>:
2608  *   </term><listitem><simpara>
2609  *    the time in 24-hour notation (<literal>\%H:\%M</literal>)
2610  *  </simpara></listitem></varlistentry>
2611  *  <varlistentry><term>
2612  *    <literal>\%s</literal>:
2613  *   </term><listitem><simpara>
2614  *    the number of seconds since the Epoch, that is, since 1970-01-01
2615  *    00:00:00 UTC
2616  *  </simpara></listitem></varlistentry>
2617  *  <varlistentry><term>
2618  *    <literal>\%S</literal>:
2619  *   </term><listitem><simpara>
2620  *    the second as a decimal number (range 00 to 60)
2621  *  </simpara></listitem></varlistentry>
2622  *  <varlistentry><term>
2623  *    <literal>\%t</literal>:
2624  *   </term><listitem><simpara>
2625  *    a tab character
2626  *  </simpara></listitem></varlistentry>
2627  *  <varlistentry><term>
2628  *    <literal>\%T</literal>:
2629  *   </term><listitem><simpara>
2630  *    the time in 24-hour notation with seconds (<literal>\%H:\%M:\%S</literal>)
2631  *  </simpara></listitem></varlistentry>
2632  *  <varlistentry><term>
2633  *    <literal>\%u</literal>:
2634  *   </term><listitem><simpara>
2635  *    the ISO 8601 standard day of the week as a decimal, range 1 to 7,
2636  *    Monday being 1.  This works well with \%G and \%V.
2637  *  </simpara></listitem></varlistentry>
2638  *  <varlistentry><term>
2639  *    <literal>\%V</literal>:
2640  *   </term><listitem><simpara>
2641  *    the ISO 8601 standard week number of the current year as a decimal
2642  *    number, range 01 to 53, where week 1 is the first week that has at
2643  *    least 4 days in the new year. See g_date_time_get_week_of_year().
2644  *    This works well with \%G and \%u.
2645  *  </simpara></listitem></varlistentry>
2646  *  <varlistentry><term>
2647  *    <literal>\%w</literal>:
2648  *   </term><listitem><simpara>
2649  *    the day of the week as a decimal, range 0 to 6, Sunday being 0.
2650  *    This is not the ISO 8601 standard format -- use \%u instead.
2651  *  </simpara></listitem></varlistentry>
2652  *  <varlistentry><term>
2653  *    <literal>\%x</literal>:
2654  *   </term><listitem><simpara>
2655  *    the preferred date representation for the current locale without
2656  *    the time
2657  *  </simpara></listitem></varlistentry>
2658  *  <varlistentry><term>
2659  *    <literal>\%X</literal>:
2660  *   </term><listitem><simpara>
2661  *    the preferred time representation for the current locale without
2662  *    the date
2663  *  </simpara></listitem></varlistentry>
2664  *  <varlistentry><term>
2665  *    <literal>\%y</literal>:
2666  *   </term><listitem><simpara>
2667  *    the year as a decimal number without the century
2668  *  </simpara></listitem></varlistentry>
2669  *  <varlistentry><term>
2670  *    <literal>\%Y</literal>:
2671  *   </term><listitem><simpara>
2672  *    the year as a decimal number including the century
2673  *  </simpara></listitem></varlistentry>
2674  *  <varlistentry><term>
2675  *    <literal>\%z</literal>:
2676  *   </term><listitem><simpara>
2677  *    the time-zone as hour offset from UTC
2678  *  </simpara></listitem></varlistentry>
2679  *  <varlistentry><term>
2680  *    <literal>\%Z</literal>:
2681  *   </term><listitem><simpara>
2682  *    the time zone or name or abbreviation
2683  *  </simpara></listitem></varlistentry>
2684  *  <varlistentry><term>
2685  *    <literal>\%\%</literal>:
2686  *   </term><listitem><simpara>
2687  *    a literal <literal>\%</literal> character
2688  *  </simpara></listitem></varlistentry>
2689  * </variablelist>
2690  *
2691  * Some conversion specifications can be modified by preceding the
2692  * conversion specifier by one or more modifier characters. The
2693  * following modifiers are supported for many of the numeric
2694  * conversions:
2695  * <variablelist>
2696  *   <varlistentry>
2697  *     <term>O</term>
2698  *     <listitem>
2699  *       Use alternative numeric symbols, if the current locale
2700  *       supports those.
2701  *     </listitem>
2702  *   </varlistentry>
2703  *   <varlistentry>
2704  *     <term>_</term>
2705  *     <listitem>
2706  *       Pad a numeric result with spaces.
2707  *       This overrides the default padding for the specifier.
2708  *     </listitem>
2709  *   </varlistentry>
2710  *   <varlistentry>
2711  *     <term>-</term>
2712  *     <listitem>
2713  *       Do not pad a numeric result.
2714  *       This overrides the default padding for the specifier.
2715  *     </listitem>
2716  *   </varlistentry>
2717  *   <varlistentry>
2718  *     <term>0</term>
2719  *     <listitem>
2720  *       Pad a numeric result with zeros.
2721  *       This overrides the default padding for the specifier.
2722  *     </listitem>
2723  *   </varlistentry>
2724  * </variablelist>
2725  *
2726  * Returns: a newly allocated string formatted to the requested format
2727  *          or %NULL in the case that there was an error.  The string
2728  *          should be freed with g_free().
2729  *
2730  * Since: 2.26
2731  */
2732 gchar *
2733 g_date_time_format (GDateTime   *datetime,
2734                     const gchar *format)
2735 {
2736   GString  *outstr;
2737   gchar *utf8;
2738   gboolean locale_is_utf8 = g_get_charset (NULL);
2739
2740   g_return_val_if_fail (datetime != NULL, NULL);
2741   g_return_val_if_fail (format != NULL, NULL);
2742   g_return_val_if_fail (g_utf8_validate (format, -1, NULL), NULL);
2743
2744   outstr = g_string_sized_new (strlen (format) * 2);
2745
2746   if (!g_date_time_format_locale (datetime, format, outstr, locale_is_utf8))
2747     {
2748       g_string_free (outstr, TRUE);
2749       return NULL;
2750     }
2751
2752   if (locale_is_utf8)
2753     return g_string_free (outstr, FALSE);
2754
2755   utf8 = g_locale_to_utf8 (outstr->str, outstr->len, NULL, NULL, NULL);
2756   g_string_free (outstr, TRUE);
2757   return utf8;
2758 }
2759
2760
2761 /* Epilogue {{{1 */
2762 /* vim:set foldmethod=marker: */