Coverage Report

Created: 2026-12-01 06:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/rauc/subprojects/glib-2.90.1/glib/gdatetime.c
Line
Count
Source
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
 * Copyright © 2018 Tomasz Miąsko
8
 * Copyright 2023 GNOME Foundation Inc.
9
 *
10
 * SPDX-License-Identifier: LGPL-2.1-or-later
11
 *
12
 * This library is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU Lesser General Public License as
14
 * published by the Free Software Foundation; either version 2.1 of the
15
 * licence, or (at your option) any later version.
16
 *
17
 * This is distributed in the hope that it will be useful, but WITHOUT
18
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
20
 * License for more details.
21
 *
22
 * You should have received a copy of the GNU Lesser General Public License
23
 * along with this library; if not, see <http://www.gnu.org/licenses/>.
24
 *
25
 * Authors: Christian Hergert <chris@dronelabs.com>
26
 *          Thiago Santos <thiago.sousa.santos@collabora.co.uk>
27
 *          Emmanuele Bassi <ebassi@linux.intel.com>
28
 *          Ryan Lortie <desrt@desrt.ca>
29
 *          Robert Ancell <robert.ancell@canonical.com>
30
 *          Philip Withnall <pwithnall@gnome.org>
31
 */
32
33
/* Algorithms within this file are based on the Calendar FAQ by
34
 * Claus Tondering.  It can be found at
35
 * http://www.tondering.dk/claus/cal/calendar29.txt
36
 *
37
 * Copyright and disclaimer
38
 * ------------------------
39
 *   This document is Copyright (C) 2008 by Claus Tondering.
40
 *   E-mail: claus@tondering.dk. (Please include the word
41
 *   "calendar" in the subject line.)
42
 *   The document may be freely distributed, provided this
43
 *   copyright notice is included and no money is charged for
44
 *   the document.
45
 *
46
 *   This document is provided "as is". No warranties are made as
47
 *   to its correctness.
48
 */
49
50
/* Prologue {{{1 */
51
52
#include "config.h"
53
54
/* langinfo.h in glibc 2.27 defines ALTMON_* only if _GNU_SOURCE is defined.  */
55
#ifndef _GNU_SOURCE
56
#define _GNU_SOURCE 1
57
#endif
58
59
#include <locale.h>
60
#include <math.h>
61
#include <stdlib.h>
62
#include <string.h>
63
64
#ifdef HAVE_LANGINFO_TIME
65
#include <langinfo.h>
66
#endif
67
68
#include "glib-private.h"
69
#include "gatomic.h"
70
#include "gcharset.h"
71
#include "gcharsetprivate.h"
72
#include "gconvert.h"
73
#include "gconvertprivate.h"
74
#include "gdatetime.h"
75
#include "gdatetime-private.h"
76
#include "gfileutils.h"
77
#include "ghash.h"
78
#include "glibintl.h"
79
#include "gmain.h"
80
#include "gmappedfile.h"
81
#include "gslice.h"
82
#include "gstrfuncs.h"
83
#include "gtestutils.h"
84
#include "gthread.h"
85
#include "gtimezone.h"
86
#include "gutilsprivate.h"
87
88
#ifndef G_OS_WIN32
89
#include <sys/time.h>
90
#include <time.h>
91
#endif /* !G_OS_WIN32 */
92
93
struct _GDateTime
94
{
95
  /* Microsecond timekeeping within Day */
96
  guint64 usec;
97
98
  /* TimeZone information */
99
  GTimeZone *tz;
100
  gint interval;
101
102
  /* 1 is 0001-01-01 in Proleptic Gregorian */
103
  gint32 days;  /* in range [MIN_DAYS, MAX_DAYS] */
104
105
  gint ref_count;  /* (atomic) */
106
};
107
108
/* Time conversion {{{1 */
109
110
0
#define UNIX_EPOCH_START     719163
111
#define INSTANT_TO_UNIX(instant) \
112
0
  ((instant)/USEC_PER_SECOND - UNIX_EPOCH_START * SEC_PER_DAY)
113
#define INSTANT_TO_UNIX_USECS(instant) \
114
0
  ((instant) - UNIX_EPOCH_START * SEC_PER_DAY * USEC_PER_SECOND)
115
#define UNIX_TO_INSTANT(unix) \
116
0
  (((gint64) (unix) + UNIX_EPOCH_START * SEC_PER_DAY) * USEC_PER_SECOND)
117
#define UNIX_USECS_TO_INSTANT(unix_usecs) \
118
0
  ((gint64) (unix_usecs) + UNIX_EPOCH_START * SEC_PER_DAY * USEC_PER_SECOND)
119
#define UNIX_TO_INSTANT_IS_VALID(unix) \
120
0
  ((gint64) (unix) <= INSTANT_TO_UNIX (G_MAXINT64))
121
#define UNIX_USECS_TO_INSTANT_IS_VALID(unix_usecs) \
122
0
  ((gint64) (unix_usecs) <= INSTANT_TO_UNIX_USECS (G_MAXINT64))
123
124
0
#define DAYS_IN_4YEARS    1461    /* days in 4 years */
125
0
#define DAYS_IN_100YEARS  36524   /* days in 100 years */
126
0
#define DAYS_IN_400YEARS  146097  /* days in 400 years  */
127
128
0
#define USEC_PER_SECOND      (G_GINT64_CONSTANT (1000000))
129
0
#define USEC_PER_MINUTE      (G_GINT64_CONSTANT (60000000))
130
0
#define USEC_PER_HOUR        (G_GINT64_CONSTANT (3600000000))
131
#define USEC_PER_MILLISECOND (G_GINT64_CONSTANT (1000))
132
0
#define USEC_PER_DAY         (G_GINT64_CONSTANT (86400000000))
133
0
#define SEC_PER_DAY          (G_GINT64_CONSTANT (86400))
134
135
0
#define SECS_PER_MINUTE (60)
136
0
#define SECS_PER_HOUR   (60 * SECS_PER_MINUTE)
137
#define SECS_PER_DAY    (24 * SECS_PER_HOUR)
138
#define SECS_PER_YEAR   (365 * SECS_PER_DAY)
139
#define SECS_PER_JULIAN (DAYS_PER_PERIOD * SECS_PER_DAY)
140
141
0
#define GREGORIAN_LEAP(y)    ((((y) % 4) == 0) && (!((((y) % 100) == 0) && (((y) % 400) != 0))))
142
#define JULIAN_YEAR(d)       ((d)->julian / 365.25)
143
#define DAYS_PER_PERIOD      (G_GINT64_CONSTANT (2914695))
144
145
0
#define MIN_DAYS 1  /* the days count for 0001-01-01 in Proleptic Gregorian */
146
0
#define MAX_DAYS 3652059  /* the days count for 9999-12-31 in Proleptic Gregorian */
147
148
static const guint16 days_in_months[2][13] =
149
{
150
  { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
151
  { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
152
};
153
154
static const guint16 days_in_year[2][13] =
155
{
156
  {  0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
157
  {  0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
158
};
159
160
#ifdef HAVE_LANGINFO_TIME
161
162
0
#define GET_AMPM(d) ((g_date_time_get_hour (d) < 12) ? \
163
0
                     nl_langinfo (AM_STR) : \
164
0
                     nl_langinfo (PM_STR))
165
0
#define GET_AMPM_IS_LOCALE TRUE
166
167
0
#define PREFERRED_DATE_TIME_FMT nl_langinfo (D_T_FMT)
168
0
#define PREFERRED_DATE_FMT nl_langinfo (D_FMT)
169
0
#define PREFERRED_TIME_FMT nl_langinfo (T_FMT)
170
0
#define PREFERRED_12HR_TIME_FMT nl_langinfo (T_FMT_AMPM)
171
172
static const gint weekday_item[2][7] =
173
{
174
  { ABDAY_2, ABDAY_3, ABDAY_4, ABDAY_5, ABDAY_6, ABDAY_7, ABDAY_1 },
175
  { DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7, DAY_1 }
176
};
177
178
static const gint month_item[2][12] =
179
{
180
  { ABMON_1, ABMON_2, ABMON_3, ABMON_4, ABMON_5, ABMON_6, ABMON_7, ABMON_8, ABMON_9, ABMON_10, ABMON_11, ABMON_12 },
181
  { MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7, MON_8, MON_9, MON_10, MON_11, MON_12 },
182
};
183
184
0
#define WEEKDAY_ABBR(d) nl_langinfo (weekday_item[0][g_date_time_get_day_of_week (d) - 1])
185
0
#define WEEKDAY_ABBR_IS_LOCALE TRUE
186
0
#define WEEKDAY_FULL(d) nl_langinfo (weekday_item[1][g_date_time_get_day_of_week (d) - 1])
187
0
#define WEEKDAY_FULL_IS_LOCALE TRUE
188
0
#define MONTH_ABBR(d) nl_langinfo (month_item[0][g_date_time_get_month (d) - 1])
189
0
#define MONTH_ABBR_IS_LOCALE TRUE
190
0
#define MONTH_FULL(d) nl_langinfo (month_item[1][g_date_time_get_month (d) - 1])
191
0
#define MONTH_FULL_IS_LOCALE TRUE
192
193
#else
194
195
#define GET_AMPM(d)          (get_fallback_ampm (g_date_time_get_hour (d)))
196
#define GET_AMPM_IS_LOCALE   FALSE
197
198
/* Translators: this is the preferred format for expressing the date and the time */
199
#define PREFERRED_DATE_TIME_FMT C_("GDateTime", "%a %b %e %H:%M:%S %Y")
200
201
/* Translators: this is the preferred format for expressing the date */
202
#define PREFERRED_DATE_FMT C_("GDateTime", "%m/%d/%y")
203
204
/* Translators: this is the preferred format for expressing the time */
205
#define PREFERRED_TIME_FMT C_("GDateTime", "%H:%M:%S")
206
207
/* Translators: this is the preferred format for expressing 12 hour time */
208
#define PREFERRED_12HR_TIME_FMT C_("GDateTime", "%I:%M:%S %p")
209
210
#define WEEKDAY_ABBR(d)       (get_weekday_name_abbr (g_date_time_get_day_of_week (d)))
211
#define WEEKDAY_ABBR_IS_LOCALE FALSE
212
#define WEEKDAY_FULL(d)       (get_weekday_name (g_date_time_get_day_of_week (d)))
213
#define WEEKDAY_FULL_IS_LOCALE FALSE
214
/* We don't yet know if nl_langinfo (MON_n) returns standalone or complete-date
215
 * format forms but if nl_langinfo (ALTMON_n) is not supported then we will
216
 * have to use MONTH_FULL as standalone.  The same if nl_langinfo () does not
217
 * exist at all.  MONTH_ABBR is similar: if nl_langinfo (_NL_ABALTMON_n) is not
218
 * supported then we will use MONTH_ABBR as standalone.
219
 */
220
#define MONTH_ABBR(d)         (get_month_name_abbr_standalone (g_date_time_get_month (d)))
221
#define MONTH_ABBR_IS_LOCALE  FALSE
222
#define MONTH_FULL(d)         (get_month_name_standalone (g_date_time_get_month (d)))
223
#define MONTH_FULL_IS_LOCALE  FALSE
224
225
static const gchar *
226
get_month_name_standalone (gint month)
227
{
228
  switch (month)
229
    {
230
    case 1:
231
      /* Translators: Some languages (Baltic, Slavic, Greek, and some more)
232
       * need different grammatical forms of month names depending on whether
233
       * they are standalone or in a complete date context, with the day
234
       * number.  Some other languages may prefer starting with uppercase when
235
       * they are standalone and with lowercase when they are in a complete
236
       * date context.  Here are full month names in a form appropriate when
237
       * they are used standalone.  If your system is Linux with the glibc
238
       * version 2.27 (released Feb 1, 2018) or newer or if it is from the BSD
239
       * family (which includes OS X) then you can refer to the date command
240
       * line utility and see what the command `date +%OB' produces.  Also in
241
       * the latest Linux the command `locale alt_mon' in your native locale
242
       * produces a complete list of month names almost ready to copy and
243
       * paste here.  Note that in most of the languages (western European,
244
       * non-European) there is no difference between the standalone and
245
       * complete date form.
246
       */
247
      return C_("full month name", "January");
248
    case 2:
249
      return C_("full month name", "February");
250
    case 3:
251
      return C_("full month name", "March");
252
    case 4:
253
      return C_("full month name", "April");
254
    case 5:
255
      return C_("full month name", "May");
256
    case 6:
257
      return C_("full month name", "June");
258
    case 7:
259
      return C_("full month name", "July");
260
    case 8:
261
      return C_("full month name", "August");
262
    case 9:
263
      return C_("full month name", "September");
264
    case 10:
265
      return C_("full month name", "October");
266
    case 11:
267
      return C_("full month name", "November");
268
    case 12:
269
      return C_("full month name", "December");
270
271
    default:
272
      g_warning ("Invalid month number %d", month);
273
    }
274
275
  return NULL;
276
}
277
278
static const gchar *
279
get_month_name_abbr_standalone (gint month)
280
{
281
  switch (month)
282
    {
283
    case 1:
284
      /* Translators: Some languages need different grammatical forms of
285
       * month names depending on whether they are standalone or in a complete
286
       * date context, with the day number.  Some may prefer starting with
287
       * uppercase when they are standalone and with lowercase when they are
288
       * in a full date context.  However, as these names are abbreviated
289
       * the grammatical difference is visible probably only in Belarusian
290
       * and Russian.  In other languages there is no difference between
291
       * the standalone and complete date form when they are abbreviated.
292
       * If your system is Linux with the glibc version 2.27 (released
293
       * Feb 1, 2018) or newer then you can refer to the date command line
294
       * utility and see what the command `date +%Ob' produces.  Also in
295
       * the latest Linux the command `locale ab_alt_mon' in your native
296
       * locale produces a complete list of month names almost ready to copy
297
       * and paste here.  Note that this feature is not yet supported by any
298
       * other platform.  Here are abbreviated month names in a form
299
       * appropriate when they are used standalone.
300
       */
301
      return C_("abbreviated month name", "Jan");
302
    case 2:
303
      return C_("abbreviated month name", "Feb");
304
    case 3:
305
      return C_("abbreviated month name", "Mar");
306
    case 4:
307
      return C_("abbreviated month name", "Apr");
308
    case 5:
309
      return C_("abbreviated month name", "May");
310
    case 6:
311
      return C_("abbreviated month name", "Jun");
312
    case 7:
313
      return C_("abbreviated month name", "Jul");
314
    case 8:
315
      return C_("abbreviated month name", "Aug");
316
    case 9:
317
      return C_("abbreviated month name", "Sep");
318
    case 10:
319
      return C_("abbreviated month name", "Oct");
320
    case 11:
321
      return C_("abbreviated month name", "Nov");
322
    case 12:
323
      return C_("abbreviated month name", "Dec");
324
325
    default:
326
      g_warning ("Invalid month number %d", month);
327
    }
328
329
  return NULL;
330
}
331
332
static const gchar *
333
get_weekday_name (gint day)
334
{
335
  switch (day)
336
    {
337
    case 1:
338
      return C_("full weekday name", "Monday");
339
    case 2:
340
      return C_("full weekday name", "Tuesday");
341
    case 3:
342
      return C_("full weekday name", "Wednesday");
343
    case 4:
344
      return C_("full weekday name", "Thursday");
345
    case 5:
346
      return C_("full weekday name", "Friday");
347
    case 6:
348
      return C_("full weekday name", "Saturday");
349
    case 7:
350
      return C_("full weekday name", "Sunday");
351
352
    default:
353
      g_warning ("Invalid week day number %d", day);
354
    }
355
356
  return NULL;
357
}
358
359
static const gchar *
360
get_weekday_name_abbr (gint day)
361
{
362
  switch (day)
363
    {
364
    case 1:
365
      return C_("abbreviated weekday name", "Mon");
366
    case 2:
367
      return C_("abbreviated weekday name", "Tue");
368
    case 3:
369
      return C_("abbreviated weekday name", "Wed");
370
    case 4:
371
      return C_("abbreviated weekday name", "Thu");
372
    case 5:
373
      return C_("abbreviated weekday name", "Fri");
374
    case 6:
375
      return C_("abbreviated weekday name", "Sat");
376
    case 7:
377
      return C_("abbreviated weekday name", "Sun");
378
379
    default:
380
      g_warning ("Invalid week day number %d", day);
381
    }
382
383
  return NULL;
384
}
385
386
#endif  /* HAVE_LANGINFO_TIME */
387
388
#ifdef HAVE_LANGINFO_ALTMON
389
390
/* If nl_langinfo () supports ALTMON_n then MON_n returns full date format
391
 * forms and ALTMON_n returns standalone forms.
392
 */
393
394
0
#define MONTH_FULL_WITH_DAY(d) MONTH_FULL(d)
395
0
#define MONTH_FULL_WITH_DAY_IS_LOCALE MONTH_FULL_IS_LOCALE
396
397
static const gint alt_month_item[12] =
398
{
399
  ALTMON_1, ALTMON_2, ALTMON_3, ALTMON_4, ALTMON_5, ALTMON_6,
400
  ALTMON_7, ALTMON_8, ALTMON_9, ALTMON_10, ALTMON_11, ALTMON_12
401
};
402
403
0
#define MONTH_FULL_STANDALONE(d) nl_langinfo (alt_month_item[g_date_time_get_month (d) - 1])
404
0
#define MONTH_FULL_STANDALONE_IS_LOCALE TRUE
405
406
#else
407
408
/* If nl_langinfo () does not support ALTMON_n then either MON_n returns
409
 * standalone forms or nl_langinfo (MON_n) does not work so we have defined
410
 * it as standalone form.
411
 */
412
413
#define MONTH_FULL_STANDALONE(d) MONTH_FULL(d)
414
#define MONTH_FULL_STANDALONE_IS_LOCALE MONTH_FULL_IS_LOCALE
415
#define MONTH_FULL_WITH_DAY(d) (get_month_name_with_day (g_date_time_get_month (d)))
416
#define MONTH_FULL_WITH_DAY_IS_LOCALE FALSE
417
418
static const gchar *
419
get_month_name_with_day (gint month)
420
{
421
  switch (month)
422
    {
423
    case 1:
424
      /* Translators: Some languages need different grammatical forms of
425
       * month names depending on whether they are standalone or in a full
426
       * date context, with the day number.  Some may prefer starting with
427
       * uppercase when they are standalone and with lowercase when they are
428
       * in a full date context.  Here are full month names in a form
429
       * appropriate when they are used in a full date context, with the
430
       * day number.  If your system is Linux with the glibc version 2.27
431
       * (released Feb 1, 2018) or newer or if it is from the BSD family
432
       * (which includes OS X) then you can refer to the date command line
433
       * utility and see what the command `date +%B' produces.  Also in
434
       * the latest Linux the command `locale mon' in your native locale
435
       * produces a complete list of month names almost ready to copy and
436
       * paste here.  In older Linux systems due to a bug the result is
437
       * incorrect in some languages.  Note that in most of the languages
438
       * (western European, non-European) there is no difference between the
439
       * standalone and complete date form.
440
       */
441
      return C_("full month name with day", "January");
442
    case 2:
443
      return C_("full month name with day", "February");
444
    case 3:
445
      return C_("full month name with day", "March");
446
    case 4:
447
      return C_("full month name with day", "April");
448
    case 5:
449
      return C_("full month name with day", "May");
450
    case 6:
451
      return C_("full month name with day", "June");
452
    case 7:
453
      return C_("full month name with day", "July");
454
    case 8:
455
      return C_("full month name with day", "August");
456
    case 9:
457
      return C_("full month name with day", "September");
458
    case 10:
459
      return C_("full month name with day", "October");
460
    case 11:
461
      return C_("full month name with day", "November");
462
    case 12:
463
      return C_("full month name with day", "December");
464
465
    default:
466
      g_warning ("Invalid month number %d", month);
467
    }
468
469
  return NULL;
470
}
471
472
#endif  /* HAVE_LANGINFO_ALTMON */
473
474
#ifdef HAVE_LANGINFO_ABALTMON
475
476
/* If nl_langinfo () supports _NL_ABALTMON_n then ABMON_n returns full
477
 * date format forms and _NL_ABALTMON_n returns standalone forms.
478
 */
479
480
0
#define MONTH_ABBR_WITH_DAY(d) MONTH_ABBR(d)
481
0
#define MONTH_ABBR_WITH_DAY_IS_LOCALE MONTH_ABBR_IS_LOCALE
482
483
static const gint ab_alt_month_item[12] =
484
{
485
  _NL_ABALTMON_1, _NL_ABALTMON_2, _NL_ABALTMON_3, _NL_ABALTMON_4,
486
  _NL_ABALTMON_5, _NL_ABALTMON_6, _NL_ABALTMON_7, _NL_ABALTMON_8,
487
  _NL_ABALTMON_9, _NL_ABALTMON_10, _NL_ABALTMON_11, _NL_ABALTMON_12
488
};
489
490
0
#define MONTH_ABBR_STANDALONE(d) nl_langinfo (ab_alt_month_item[g_date_time_get_month (d) - 1])
491
0
#define MONTH_ABBR_STANDALONE_IS_LOCALE TRUE
492
493
#else
494
495
/* If nl_langinfo () does not support _NL_ABALTMON_n then either ABMON_n
496
 * returns standalone forms or nl_langinfo (ABMON_n) does not work so we
497
 * have defined it as standalone form. Now it's time to swap.
498
 */
499
500
#define MONTH_ABBR_STANDALONE(d) MONTH_ABBR(d)
501
#define MONTH_ABBR_STANDALONE_IS_LOCALE MONTH_ABBR_IS_LOCALE
502
#define MONTH_ABBR_WITH_DAY(d) (get_month_name_abbr_with_day (g_date_time_get_month (d)))
503
#define MONTH_ABBR_WITH_DAY_IS_LOCALE FALSE
504
505
static const gchar *
506
get_month_name_abbr_with_day (gint month)
507
{
508
  switch (month)
509
    {
510
    case 1:
511
      /* Translators: Some languages need different grammatical forms of
512
       * month names depending on whether they are standalone or in a full
513
       * date context, with the day number.  Some may prefer starting with
514
       * uppercase when they are standalone and with lowercase when they are
515
       * in a full date context.  Here are abbreviated month names in a form
516
       * appropriate when they are used in a full date context, with the
517
       * day number.  However, as these names are abbreviated the grammatical
518
       * difference is visible probably only in Belarusian and Russian.
519
       * In other languages there is no difference between the standalone
520
       * and complete date form when they are abbreviated.  If your system
521
       * is Linux with the glibc version 2.27 (released Feb 1, 2018) or newer
522
       * then you can refer to the date command line utility and see what the
523
       * command `date +%b' produces.  Also in the latest Linux the command
524
       * `locale abmon' in your native locale produces a complete list of
525
       * month names almost ready to copy and paste here.  In other systems
526
       * due to a bug the result is incorrect in some languages.
527
       */
528
      return C_("abbreviated month name with day", "Jan");
529
    case 2:
530
      return C_("abbreviated month name with day", "Feb");
531
    case 3:
532
      return C_("abbreviated month name with day", "Mar");
533
    case 4:
534
      return C_("abbreviated month name with day", "Apr");
535
    case 5:
536
      return C_("abbreviated month name with day", "May");
537
    case 6:
538
      return C_("abbreviated month name with day", "Jun");
539
    case 7:
540
      return C_("abbreviated month name with day", "Jul");
541
    case 8:
542
      return C_("abbreviated month name with day", "Aug");
543
    case 9:
544
      return C_("abbreviated month name with day", "Sep");
545
    case 10:
546
      return C_("abbreviated month name with day", "Oct");
547
    case 11:
548
      return C_("abbreviated month name with day", "Nov");
549
    case 12:
550
      return C_("abbreviated month name with day", "Dec");
551
552
    default:
553
      g_warning ("Invalid month number %d", month);
554
    }
555
556
  return NULL;
557
}
558
559
#endif  /* HAVE_LANGINFO_ABALTMON */
560
561
/* FIXME: It doesn’t seem to be possible to use ERA on 64-bit big-endian platforms with glibc
562
 * in a POSIX-compliant way right now.
563
 * See https://gitlab.gnome.org/GNOME/glib/-/issues/3225 */
564
#if defined(HAVE_LANGINFO_ERA) && (G_BYTE_ORDER == G_LITTLE_ENDIAN || GLIB_SIZEOF_VOID_P == 4)
565
566
0
#define PREFERRED_ERA_DATE_TIME_FMT nl_langinfo (ERA_D_T_FMT)
567
0
#define PREFERRED_ERA_DATE_FMT nl_langinfo (ERA_D_FMT)
568
0
#define PREFERRED_ERA_TIME_FMT nl_langinfo (ERA_T_FMT)
569
570
0
#define ERA_DESCRIPTION nl_langinfo (ERA)
571
0
#define ERA_DESCRIPTION_IS_LOCALE TRUE
572
0
#define ERA_DESCRIPTION_N_SEGMENTS (int) (gintptr) nl_langinfo (_NL_TIME_ERA_NUM_ENTRIES)
573
574
#else  /* if !HAVE_LANGINFO_ERA */
575
576
#define PREFERRED_ERA_DATE_TIME_FMT PREFERRED_DATE_TIME_FMT
577
#define PREFERRED_ERA_DATE_FMT PREFERRED_DATE_FMT
578
#define PREFERRED_ERA_TIME_FMT PREFERRED_TIME_FMT
579
580
#define ERA_DESCRIPTION NULL
581
#define ERA_DESCRIPTION_IS_LOCALE FALSE
582
#define ERA_DESCRIPTION_N_SEGMENTS 0
583
584
#endif  /* !HAVE_LANGINFO_ERA */
585
586
/* Format AM/PM indicator if the locale does not have a localized version. */
587
static const gchar *
588
get_fallback_ampm (gint hour)
589
0
{
590
0
  if (hour < 12)
591
    /* Translators: 'before midday' indicator */
592
0
    return C_("GDateTime", "AM");
593
0
  else
594
    /* Translators: 'after midday' indicator */
595
0
    return C_("GDateTime", "PM");
596
0
}
597
598
static inline gint
599
ymd_to_days (gint year,
600
             gint month,
601
             gint day)
602
0
{
603
0
  gint64 days;
604
605
0
  days = ((gint64) year - 1) * 365 + ((year - 1) / 4) - ((year - 1) / 100)
606
0
      + ((year - 1) / 400);
607
608
0
  days += days_in_year[0][month - 1];
609
0
  if (GREGORIAN_LEAP (year) && month > 2)
610
0
    day++;
611
612
0
  days += day;
613
614
0
  return days;
615
0
}
616
617
static void
618
g_date_time_get_week_number (GDateTime *datetime,
619
                             gint      *week_number,
620
                             gint      *day_of_week,
621
                             gint      *day_of_year)
622
0
{
623
0
  gint a, b, c, d, e, f, g, n, s, month = -1, day = -1, year = -1;
624
625
0
  g_date_time_get_ymd (datetime, &year, &month, &day);
626
627
0
  if (month <= 2)
628
0
    {
629
0
      a = g_date_time_get_year (datetime) - 1;
630
0
      b = (a / 4) - (a / 100) + (a / 400);
631
0
      c = ((a - 1) / 4) - ((a - 1) / 100) + ((a - 1) / 400);
632
0
      s = b - c;
633
0
      e = 0;
634
0
      f = day - 1 + (31 * (month - 1));
635
0
    }
636
0
  else
637
0
    {
638
0
      a = year;
639
0
      b = (a / 4) - (a / 100) + (a / 400);
640
0
      c = ((a - 1) / 4) - ((a - 1) / 100) + ((a - 1) / 400);
641
0
      s = b - c;
642
0
      e = s + 1;
643
0
      f = day + (((153 * (month - 3)) + 2) / 5) + 58 + s;
644
0
    }
645
646
0
  g = (a + b) % 7;
647
0
  d = (f + g - e) % 7;
648
0
  n = f + 3 - d;
649
650
0
  if (week_number)
651
0
    {
652
0
      if (n < 0)
653
0
        *week_number = 53 - ((g - s) / 5);
654
0
      else if (n > 364 + s)
655
0
        *week_number = 1;
656
0
      else
657
0
        *week_number = (n / 7) + 1;
658
0
    }
659
660
0
  if (day_of_week)
661
0
    *day_of_week = d + 1;
662
663
0
  if (day_of_year)
664
0
    *day_of_year = f + 1;
665
0
}
666
667
/* Lifecycle {{{1 */
668
669
static GDateTime *
670
g_date_time_alloc (GTimeZone *tz)
671
0
{
672
0
  GDateTime *datetime;
673
674
0
  datetime = g_slice_new0 (GDateTime);
675
0
  datetime->tz = g_time_zone_ref (tz);
676
0
  datetime->ref_count = 1;
677
678
0
  return datetime;
679
0
}
680
681
/**
682
 * g_date_time_ref:
683
 * @datetime: a #GDateTime
684
 *
685
 * Atomically increments the reference count of @datetime by one.
686
 *
687
 * Returns: the #GDateTime with the reference count increased
688
 *
689
 * Since: 2.26
690
 */
691
GDateTime *
692
g_date_time_ref (GDateTime *datetime)
693
0
{
694
0
  g_return_val_if_fail (datetime != NULL, NULL);
695
0
  g_return_val_if_fail (datetime->ref_count > 0, NULL);
696
697
0
  g_atomic_int_inc (&datetime->ref_count);
698
699
0
  return datetime;
700
0
}
701
702
/**
703
 * g_date_time_unref:
704
 * @datetime: a #GDateTime
705
 *
706
 * Atomically decrements the reference count of @datetime by one.
707
 *
708
 * When the reference count reaches zero, the resources allocated by
709
 * @datetime are freed
710
 *
711
 * Since: 2.26
712
 */
713
void
714
g_date_time_unref (GDateTime *datetime)
715
0
{
716
0
  g_return_if_fail (datetime != NULL);
717
0
  g_return_if_fail (datetime->ref_count > 0);
718
719
0
  if (g_atomic_int_dec_and_test (&datetime->ref_count))
720
0
    {
721
0
      g_time_zone_unref (datetime->tz);
722
0
      g_slice_free (GDateTime, datetime);
723
0
    }
724
0
}
725
726
/* Internal state transformers {{{1 */
727
/*< internal >
728
 * g_date_time_to_instant:
729
 * @datetime: a #GDateTime
730
 *
731
 * Convert a @datetime into an instant.
732
 *
733
 * An instant is a number that uniquely describes a particular
734
 * microsecond in time, taking time zone considerations into account.
735
 * (ie: "03:00 -0400" is the same instant as "02:00 -0500").
736
 *
737
 * An instant is always positive but we use a signed return value to
738
 * avoid troubles with C.
739
 */
740
static gint64
741
g_date_time_to_instant (GDateTime *datetime)
742
0
{
743
0
  gint64 offset;
744
745
0
  offset = g_time_zone_get_offset (datetime->tz, datetime->interval);
746
0
  offset *= USEC_PER_SECOND;
747
748
0
  return datetime->days * USEC_PER_DAY + datetime->usec - offset;
749
0
}
750
751
/*< internal >
752
 * g_date_time_from_instant:
753
 * @tz: a #GTimeZone
754
 * @instant: an instant in time
755
 *
756
 * Creates a #GDateTime from a time zone and an instant.
757
 *
758
 * This might fail if the time ends up being out of range.
759
 */
760
static GDateTime *
761
g_date_time_from_instant (GTimeZone *tz,
762
                          gint64     instant)
763
0
{
764
0
  GDateTime *datetime;
765
0
  gint64 offset;
766
767
0
  if (instant < 0 || instant > G_GINT64_CONSTANT (1000000000000000000))
768
0
    return NULL;
769
770
0
  datetime = g_date_time_alloc (tz);
771
0
  datetime->interval = g_time_zone_find_interval (tz,
772
0
                                                  G_TIME_TYPE_UNIVERSAL,
773
0
                                                  INSTANT_TO_UNIX (instant));
774
0
  offset = g_time_zone_get_offset (datetime->tz, datetime->interval);
775
0
  offset *= USEC_PER_SECOND;
776
777
0
  instant += offset;
778
779
0
  datetime->days = instant / USEC_PER_DAY;
780
0
  datetime->usec = instant % USEC_PER_DAY;
781
782
0
  if (datetime->days < MIN_DAYS || datetime->days > MAX_DAYS)
783
0
    {
784
0
      g_date_time_unref (datetime);
785
0
      datetime = NULL;
786
0
    }
787
788
0
  return datetime;
789
0
}
790
791
792
/*< internal >
793
 * g_date_time_deal_with_date_change:
794
 * @datetime: a #GDateTime
795
 *
796
 * This function should be called whenever the date changes by adding
797
 * days, months or years.  It does three things.
798
 *
799
 * First, we ensure that the date falls between 0001-01-01 and
800
 * 9999-12-31 and return %FALSE if it does not.
801
 *
802
 * Next we update the ->interval field.
803
 *
804
 * Finally, we ensure that the resulting date and time pair exists (by
805
 * ensuring that our time zone has an interval containing it) and
806
 * adjusting as required.  For example, if we have the time 02:30:00 on
807
 * March 13 2010 in Toronto and we add 1 day to it, we would end up with
808
 * 2:30am on March 14th, which doesn't exist.  In that case, we bump the
809
 * time up to 3:00am.
810
 */
811
static gboolean
812
g_date_time_deal_with_date_change (GDateTime *datetime)
813
0
{
814
0
  GTimeType was_dst;
815
0
  gint64 full_time;
816
0
  gint64 usec;
817
818
0
  if (datetime->days < MIN_DAYS || datetime->days > MAX_DAYS)
819
0
    return FALSE;
820
821
0
  was_dst = g_time_zone_is_dst (datetime->tz, datetime->interval);
822
823
0
  full_time = datetime->days * USEC_PER_DAY + datetime->usec;
824
825
826
0
  usec = full_time % USEC_PER_SECOND;
827
0
  full_time /= USEC_PER_SECOND;
828
0
  full_time -= UNIX_EPOCH_START * SEC_PER_DAY;
829
830
0
  datetime->interval = g_time_zone_adjust_time (datetime->tz,
831
0
                                                was_dst,
832
0
                                                &full_time);
833
0
  full_time += UNIX_EPOCH_START * SEC_PER_DAY;
834
0
  full_time *= USEC_PER_SECOND;
835
0
  full_time += usec;
836
837
0
  datetime->days = full_time / USEC_PER_DAY;
838
0
  datetime->usec = full_time % USEC_PER_DAY;
839
840
  /* maybe daylight time caused us to shift to a different day,
841
   * but it definitely didn't push us into a different year */
842
0
  return TRUE;
843
0
}
844
845
static GDateTime *
846
g_date_time_replace_days (GDateTime *datetime,
847
                          gint       days)
848
0
{
849
0
  GDateTime *new;
850
851
0
  new = g_date_time_alloc (datetime->tz);
852
0
  new->interval = datetime->interval;
853
0
  new->usec = datetime->usec;
854
0
  new->days = days;
855
856
0
  if (!g_date_time_deal_with_date_change (new))
857
0
    {
858
0
      g_date_time_unref (new);
859
0
      new = NULL;
860
0
    }
861
862
0
  return new;
863
0
}
864
865
/* now/unix/timeval Constructors {{{1 */
866
867
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
868
/*< internal >
869
 * g_date_time_new_from_timeval:
870
 * @tz: a #GTimeZone
871
 * @tv: a #GTimeVal
872
 *
873
 * Creates a #GDateTime corresponding to the given #GTimeVal @tv in the
874
 * given time zone @tz.
875
 *
876
 * The time contained in a #GTimeVal is always stored in the form of
877
 * seconds elapsed since 1970-01-01 00:00:00 UTC, regardless of the
878
 * given time zone.
879
 *
880
 * This call can fail (returning %NULL) if @tv represents a time outside
881
 * of the supported range of #GDateTime.
882
 *
883
 * You should release the return value by calling g_date_time_unref()
884
 * when you are done with it.
885
 *
886
 * Returns: a new #GDateTime, or %NULL
887
 *
888
 * Since: 2.26
889
 **/
890
static GDateTime *
891
g_date_time_new_from_timeval (GTimeZone      *tz,
892
                              const GTimeVal *tv)
893
0
{
894
0
  gint64 tv_sec = tv->tv_sec;
895
896
0
  if (tv_sec > G_MAXINT64 - 1 || !UNIX_TO_INSTANT_IS_VALID (tv_sec + 1))
897
0
    return NULL;
898
899
0
  return g_date_time_from_instant (tz, tv->tv_usec +
900
0
                                   UNIX_TO_INSTANT (tv->tv_sec));
901
0
}
902
G_GNUC_END_IGNORE_DEPRECATIONS
903
904
/*< internal >
905
 * g_date_time_new_from_unix:
906
 * @tz: a #GTimeZone
907
 * @usecs: the Unix time, in microseconds since the epoch
908
 *
909
 * Creates a #GDateTime corresponding to the given Unix time @t_us in the
910
 * given time zone @tz.
911
 *
912
 * Unix time is the number of seconds that have elapsed since 1970-01-01
913
 * 00:00:00 UTC, regardless of the time zone given.
914
 *
915
 * This call can fail (returning %NULL) if @t represents a time outside
916
 * of the supported range of #GDateTime.
917
 *
918
 * You should release the return value by calling g_date_time_unref()
919
 * when you are done with it.
920
 *
921
 * Returns: a new #GDateTime, or %NULL
922
 *
923
 * Since: 2.26
924
 **/
925
static GDateTime *
926
g_date_time_new_from_unix (GTimeZone *tz,
927
                           gint64     usecs)
928
0
{
929
0
  if (!UNIX_USECS_TO_INSTANT_IS_VALID (usecs))
930
0
    return NULL;
931
932
0
  return g_date_time_from_instant (tz, UNIX_USECS_TO_INSTANT (usecs));
933
0
}
934
935
/**
936
 * g_date_time_new_now: (constructor)
937
 * @tz: a #GTimeZone
938
 *
939
 * Creates a #GDateTime corresponding to this exact instant in the given
940
 * time zone @tz.  The time is as accurate as the system allows, to a
941
 * maximum accuracy of 1 microsecond.
942
 *
943
 * This function will always succeed unless GLib is still being used after the
944
 * year 9999.
945
 *
946
 * You should release the return value by calling g_date_time_unref()
947
 * when you are done with it.
948
 *
949
 * Returns: (transfer full) (nullable): a new #GDateTime, or %NULL
950
 *
951
 * Since: 2.26
952
 **/
953
GDateTime *
954
g_date_time_new_now (GTimeZone *tz)
955
0
{
956
0
  gint64 now_us;
957
958
0
  g_return_val_if_fail (tz != NULL, NULL);
959
960
0
  now_us = g_get_real_time ();
961
962
0
  return g_date_time_new_from_unix (tz, now_us);
963
0
}
964
965
/**
966
 * g_date_time_new_now_local: (constructor)
967
 *
968
 * Creates a #GDateTime corresponding to this exact instant in the local
969
 * time zone.
970
 *
971
 * This is equivalent to calling g_date_time_new_now() with the time
972
 * zone returned by g_time_zone_new_local().
973
 *
974
 * Returns: (transfer full) (nullable): a new #GDateTime, or %NULL
975
 *
976
 * Since: 2.26
977
 **/
978
GDateTime *
979
g_date_time_new_now_local (void)
980
0
{
981
0
  GDateTime *datetime;
982
0
  GTimeZone *local;
983
984
0
  local = g_time_zone_new_local ();
985
0
  datetime = g_date_time_new_now (local);
986
0
  g_time_zone_unref (local);
987
988
0
  return datetime;
989
0
}
990
991
/**
992
 * g_date_time_new_now_utc: (constructor)
993
 *
994
 * Creates a #GDateTime corresponding to this exact instant in UTC.
995
 *
996
 * This is equivalent to calling g_date_time_new_now() with the time
997
 * zone returned by g_time_zone_new_utc().
998
 *
999
 * Returns: (transfer full) (nullable): a new #GDateTime, or %NULL
1000
 *
1001
 * Since: 2.26
1002
 **/
1003
GDateTime *
1004
g_date_time_new_now_utc (void)
1005
0
{
1006
0
  GDateTime *datetime;
1007
0
  GTimeZone *utc;
1008
1009
0
  utc = g_time_zone_new_utc ();
1010
0
  datetime = g_date_time_new_now (utc);
1011
0
  g_time_zone_unref (utc);
1012
1013
0
  return datetime;
1014
0
}
1015
1016
/**
1017
 * g_date_time_new_from_unix_local: (constructor)
1018
 * @t: the Unix time
1019
 *
1020
 * Creates a #GDateTime corresponding to the given Unix time @t in the
1021
 * local time zone.
1022
 *
1023
 * Unix time is the number of seconds that have elapsed since 1970-01-01
1024
 * 00:00:00 UTC, regardless of the local time offset.
1025
 *
1026
 * This call can fail (returning %NULL) if @t represents a time outside
1027
 * of the supported range of #GDateTime.
1028
 *
1029
 * You should release the return value by calling g_date_time_unref()
1030
 * when you are done with it.
1031
 *
1032
 * Returns: (transfer full) (nullable): a new #GDateTime, or %NULL
1033
 *
1034
 * Since: 2.26
1035
 **/
1036
GDateTime *
1037
g_date_time_new_from_unix_local (gint64 t)
1038
0
{
1039
0
  if (t > G_MAXINT64 / USEC_PER_SECOND ||
1040
0
      t < G_MININT64 / USEC_PER_SECOND)
1041
0
    return NULL;
1042
1043
0
  return g_date_time_new_from_unix_local_usec (t * USEC_PER_SECOND);
1044
0
}
1045
1046
/**
1047
 * g_date_time_new_from_unix_local_usec: (constructor)
1048
 * @usecs: the Unix time in microseconds
1049
 *
1050
 * Creates a [struct@GLib.DateTime] corresponding to the given Unix time @t in the
1051
 * local time zone.
1052
 *
1053
 * Unix time is the number of microseconds that have elapsed since 1970-01-01
1054
 * 00:00:00 UTC, regardless of the local time offset.
1055
 *
1056
 * This call can fail (returning `NULL`) if @t represents a time outside
1057
 * of the supported range of #GDateTime.
1058
 *
1059
 * You should release the return value by calling [method@GLib.DateTime.unref]
1060
 * when you are done with it.
1061
 *
1062
 * Returns: (transfer full) (nullable): a new [struct@GLib.DateTime], or `NULL`
1063
 *
1064
 * Since: 2.80
1065
 **/
1066
GDateTime *
1067
g_date_time_new_from_unix_local_usec (gint64 usecs)
1068
0
{
1069
0
  GDateTime *datetime;
1070
0
  GTimeZone *local;
1071
1072
0
  local = g_time_zone_new_local ();
1073
0
  datetime = g_date_time_new_from_unix (local, usecs);
1074
0
  g_time_zone_unref (local);
1075
1076
0
  return datetime;
1077
0
}
1078
1079
/**
1080
 * g_date_time_new_from_unix_utc: (constructor)
1081
 * @t: the Unix time
1082
 *
1083
 * Creates a #GDateTime corresponding to the given Unix time @t in UTC.
1084
 *
1085
 * Unix time is the number of seconds that have elapsed since 1970-01-01
1086
 * 00:00:00 UTC.
1087
 *
1088
 * This call can fail (returning %NULL) if @t represents a time outside
1089
 * of the supported range of #GDateTime.
1090
 *
1091
 * You should release the return value by calling g_date_time_unref()
1092
 * when you are done with it.
1093
 *
1094
 * Returns: (transfer full) (nullable): a new #GDateTime, or %NULL
1095
 *
1096
 * Since: 2.26
1097
 **/
1098
GDateTime *
1099
g_date_time_new_from_unix_utc (gint64 t)
1100
0
{
1101
0
  if (t > G_MAXINT64 / USEC_PER_SECOND ||
1102
0
      t < G_MININT64 / USEC_PER_SECOND)
1103
0
    return NULL;
1104
1105
0
  return g_date_time_new_from_unix_utc_usec (t * USEC_PER_SECOND);
1106
0
}
1107
1108
/**
1109
 * g_date_time_new_from_unix_utc_usec: (constructor)
1110
 * @usecs: the Unix time in microseconds
1111
 *
1112
 * Creates a [struct@GLib.DateTime] corresponding to the given Unix time @t in UTC.
1113
 *
1114
 * Unix time is the number of microseconds that have elapsed since 1970-01-01
1115
 * 00:00:00 UTC.
1116
 *
1117
 * This call can fail (returning `NULL`) if @t represents a time outside
1118
 * of the supported range of #GDateTime.
1119
 *
1120
 * You should release the return value by calling [method@GLib.DateTime.unref]
1121
 * when you are done with it.
1122
 *
1123
 * Returns: (transfer full) (nullable): a new [struct@GLib.DateTime], or `NULL`
1124
 *
1125
 * Since: 2.80
1126
 **/
1127
GDateTime *
1128
g_date_time_new_from_unix_utc_usec (gint64 usecs)
1129
0
{
1130
0
  GDateTime *datetime;
1131
0
  GTimeZone *utc;
1132
1133
0
  utc = g_time_zone_new_utc ();
1134
0
  datetime = g_date_time_new_from_unix (utc, usecs);
1135
0
  g_time_zone_unref (utc);
1136
1137
0
  return datetime;
1138
0
}
1139
1140
/**
1141
 * g_date_time_new_from_timeval_local: (constructor)
1142
 * @tv: a #GTimeVal
1143
 *
1144
 * Creates a #GDateTime corresponding to the given #GTimeVal @tv in the
1145
 * local time zone.
1146
 *
1147
 * The time contained in a #GTimeVal is always stored in the form of
1148
 * seconds elapsed since 1970-01-01 00:00:00 UTC, regardless of the
1149
 * local time offset.
1150
 *
1151
 * This call can fail (returning %NULL) if @tv represents a time outside
1152
 * of the supported range of #GDateTime.
1153
 *
1154
 * You should release the return value by calling g_date_time_unref()
1155
 * when you are done with it.
1156
 *
1157
 * Returns: (transfer full) (nullable): a new #GDateTime, or %NULL
1158
 *
1159
 * Since: 2.26
1160
 * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use
1161
 *    g_date_time_new_from_unix_local() instead.
1162
 **/
1163
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
1164
GDateTime *
1165
g_date_time_new_from_timeval_local (const GTimeVal *tv)
1166
0
{
1167
0
  GDateTime *datetime;
1168
0
  GTimeZone *local;
1169
1170
0
  local = g_time_zone_new_local ();
1171
0
  datetime = g_date_time_new_from_timeval (local, tv);
1172
0
  g_time_zone_unref (local);
1173
1174
0
  return datetime;
1175
0
}
1176
G_GNUC_END_IGNORE_DEPRECATIONS
1177
1178
/**
1179
 * g_date_time_new_from_timeval_utc: (constructor)
1180
 * @tv: a #GTimeVal
1181
 *
1182
 * Creates a #GDateTime corresponding to the given #GTimeVal @tv in UTC.
1183
 *
1184
 * The time contained in a #GTimeVal is always stored in the form of
1185
 * seconds elapsed since 1970-01-01 00:00:00 UTC.
1186
 *
1187
 * This call can fail (returning %NULL) if @tv represents a time outside
1188
 * of the supported range of #GDateTime.
1189
 *
1190
 * You should release the return value by calling g_date_time_unref()
1191
 * when you are done with it.
1192
 *
1193
 * Returns: (transfer full) (nullable): a new #GDateTime, or %NULL
1194
 *
1195
 * Since: 2.26
1196
 * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use
1197
 *    g_date_time_new_from_unix_utc() instead.
1198
 **/
1199
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
1200
GDateTime *
1201
g_date_time_new_from_timeval_utc (const GTimeVal *tv)
1202
0
{
1203
0
  GDateTime *datetime;
1204
0
  GTimeZone *utc;
1205
1206
0
  utc = g_time_zone_new_utc ();
1207
0
  datetime = g_date_time_new_from_timeval (utc, tv);
1208
0
  g_time_zone_unref (utc);
1209
1210
0
  return datetime;
1211
0
}
1212
G_GNUC_END_IGNORE_DEPRECATIONS
1213
1214
/* Parse integers in the form d (week days), dd (hours etc), ddd (ordinal days) or dddd (years) */
1215
static gboolean
1216
get_iso8601_int (const gchar *text, gsize length, gint *value)
1217
0
{
1218
0
  gsize i;
1219
0
  guint v = 0;
1220
1221
0
  if (length < 1 || length > 4)
1222
0
    return FALSE;
1223
1224
0
  for (i = 0; i < length; i++)
1225
0
    {
1226
0
      const gchar c = text[i];
1227
0
      if (c < '0' || c > '9')
1228
0
        return FALSE;
1229
0
      v = v * 10 + (c - '0');
1230
0
    }
1231
1232
0
  *value = v;
1233
0
  return TRUE;
1234
0
}
1235
1236
/* Parse seconds in the form ss or ss.sss (variable length decimal) */
1237
static gboolean
1238
get_iso8601_seconds (const gchar *text, gsize length, gdouble *value)
1239
0
{
1240
0
  gsize i;
1241
0
  guint64 divisor = 1, v = 0;
1242
1243
0
  if (length < 2)
1244
0
    return FALSE;
1245
1246
0
  for (i = 0; i < 2; i++)
1247
0
    {
1248
0
      const gchar c = text[i];
1249
0
      if (c < '0' || c > '9')
1250
0
        return FALSE;
1251
0
      v = v * 10 + (c - '0');
1252
0
    }
1253
1254
0
  if (length > 2 && !(text[i] == '.' || text[i] == ','))
1255
0
    return FALSE;
1256
1257
  /* Ignore leap seconds, see g_date_time_new_from_iso8601() */
1258
0
  if (v >= 60.0 && v <= 61.0)
1259
0
    v = 59.0;
1260
1261
0
  i++;
1262
0
  if (i == length)
1263
0
    return FALSE;
1264
1265
0
  for (; i < length; i++)
1266
0
    {
1267
0
      const gchar c = text[i];
1268
0
      if (c < '0' || c > '9' ||
1269
0
          v > (G_MAXUINT64 - (c - '0')) / 10 ||
1270
0
          divisor > G_MAXUINT64 / 10)
1271
0
        return FALSE;
1272
0
      v = v * 10 + (c - '0');
1273
0
      divisor *= 10;
1274
0
    }
1275
1276
0
  *value = (gdouble) v / divisor;
1277
0
  return TRUE;
1278
0
}
1279
1280
static GDateTime *
1281
g_date_time_new_ordinal (GTimeZone *tz, gint year, gint ordinal_day, gint hour, gint minute, gdouble seconds)
1282
0
{
1283
0
  GDateTime *dt;
1284
1285
0
  if (ordinal_day < 1 || ordinal_day > (GREGORIAN_LEAP (year) ? 366 : 365))
1286
0
    return NULL;
1287
1288
0
  dt = g_date_time_new (tz, year, 1, 1, hour, minute, seconds);
1289
0
  if (dt == NULL)
1290
0
    return NULL;
1291
0
  dt->days += ordinal_day - 1;
1292
1293
0
  return dt;
1294
0
}
1295
1296
static GDateTime *
1297
g_date_time_new_week (GTimeZone *tz, gint year, gint week, gint week_day, gint hour, gint minute, gdouble seconds)
1298
0
{
1299
0
  gint64 p;
1300
0
  gint max_week, jan4_week_day, ordinal_day;
1301
0
  GDateTime *dt;
1302
1303
0
  p = (year * 365 + (year / 4) - (year / 100) + (year / 400)) % 7;
1304
0
  max_week = p == 4 ? 53 : 52;
1305
1306
0
  if (week < 1 || week > max_week || week_day < 1 || week_day > 7)
1307
0
    return NULL;
1308
1309
0
  dt = g_date_time_new (tz, year, 1, 4, 0, 0, 0);
1310
0
  if (dt == NULL)
1311
0
    return NULL;
1312
0
  g_date_time_get_week_number (dt, NULL, &jan4_week_day, NULL);
1313
0
  g_date_time_unref (dt);
1314
1315
0
  ordinal_day = (week * 7) + week_day - (jan4_week_day + 3);
1316
0
  if (ordinal_day < 0)
1317
0
    {
1318
0
      year--;
1319
0
      ordinal_day += GREGORIAN_LEAP (year) ? 366 : 365;
1320
0
    }
1321
0
  else if (ordinal_day > (GREGORIAN_LEAP (year) ? 366 : 365))
1322
0
    {
1323
0
      ordinal_day -= (GREGORIAN_LEAP (year) ? 366 : 365);
1324
0
      year++;
1325
0
    }
1326
1327
0
  return g_date_time_new_ordinal (tz, year, ordinal_day, hour, minute, seconds);
1328
0
}
1329
1330
static GDateTime *
1331
parse_iso8601_date (const gchar *text, gsize length,
1332
                    gint hour, gint minute, gdouble seconds, GTimeZone *tz)
1333
0
{
1334
  /* YYYY-MM-DD */
1335
0
  if (length == 10 && text[4] == '-' && text[7] == '-')
1336
0
    {
1337
0
      int year, month, day;
1338
0
      if (!get_iso8601_int (text, 4, &year) ||
1339
0
          !get_iso8601_int (text + 5, 2, &month) ||
1340
0
          !get_iso8601_int (text + 8, 2, &day))
1341
0
        return NULL;
1342
0
      return g_date_time_new (tz, year, month, day, hour, minute, seconds);
1343
0
    }
1344
  /* YYYY-DDD */
1345
0
  else if (length == 8 && text[4] == '-')
1346
0
    {
1347
0
      gint year, ordinal_day;
1348
0
      if (!get_iso8601_int (text, 4, &year) ||
1349
0
          !get_iso8601_int (text + 5, 3, &ordinal_day))
1350
0
        return NULL;
1351
0
      return g_date_time_new_ordinal (tz, year, ordinal_day, hour, minute, seconds);
1352
0
    }
1353
  /* YYYY-Www-D */
1354
0
  else if (length == 10 && text[4] == '-' && text[5] == 'W' && text[8] == '-')
1355
0
    {
1356
0
      gint year, week, week_day;
1357
0
      if (!get_iso8601_int (text, 4, &year) ||
1358
0
          !get_iso8601_int (text + 6, 2, &week) ||
1359
0
          !get_iso8601_int (text + 9, 1, &week_day))
1360
0
        return NULL;
1361
0
      return g_date_time_new_week (tz, year, week, week_day, hour, minute, seconds);
1362
0
    }
1363
  /* YYYYWwwD */
1364
0
  else if (length == 8 && text[4] == 'W')
1365
0
    {
1366
0
      gint year, week, week_day;
1367
0
      if (!get_iso8601_int (text, 4, &year) ||
1368
0
          !get_iso8601_int (text + 5, 2, &week) ||
1369
0
          !get_iso8601_int (text + 7, 1, &week_day))
1370
0
        return NULL;
1371
0
      return g_date_time_new_week (tz, year, week, week_day, hour, minute, seconds);
1372
0
    }
1373
  /* YYYYMMDD */
1374
0
  else if (length == 8)
1375
0
    {
1376
0
      int year, month, day;
1377
0
      if (!get_iso8601_int (text, 4, &year) ||
1378
0
          !get_iso8601_int (text + 4, 2, &month) ||
1379
0
          !get_iso8601_int (text + 6, 2, &day))
1380
0
        return NULL;
1381
0
      return g_date_time_new (tz, year, month, day, hour, minute, seconds);
1382
0
    }
1383
  /* YYYYDDD */
1384
0
  else if (length == 7)
1385
0
    {
1386
0
      gint year, ordinal_day;
1387
0
      if (!get_iso8601_int (text, 4, &year) ||
1388
0
          !get_iso8601_int (text + 4, 3, &ordinal_day))
1389
0
        return NULL;
1390
0
      return g_date_time_new_ordinal (tz, year, ordinal_day, hour, minute, seconds);
1391
0
    }
1392
0
  else
1393
0
    return FALSE;
1394
0
}
1395
1396
/* Value returned in tz_offset is valid if and only if the function return value
1397
 * is non-NULL. */
1398
static GTimeZone *
1399
parse_iso8601_timezone (const gchar *text, gsize length, size_t *tz_offset)
1400
0
{
1401
0
  size_t tz_length;
1402
0
  gint offset_hours, offset_minutes;
1403
0
  gint offset_sign = 1;
1404
0
  GTimeZone *tz;
1405
0
  const char *tz_start;
1406
1407
  /* UTC uses Z suffix  */
1408
0
  if (length > 0 && text[length - 1] == 'Z')
1409
0
    {
1410
0
      *tz_offset = length - 1;
1411
0
      return g_time_zone_new_utc ();
1412
0
    }
1413
1414
  /* Look for '+' or '-' of offset */
1415
0
  for (tz_length = 1; tz_length <= length; tz_length++)
1416
0
    if (text[length - tz_length] == '+' || text[length - tz_length] == '-')
1417
0
      {
1418
0
        offset_sign = text[length - tz_length] == '-' ? -1 : 1;
1419
0
        break;
1420
0
      }
1421
0
  if (tz_length > length)
1422
0
    return NULL;
1423
0
  tz_start = text + length - tz_length;
1424
1425
  /* +hh:mm or -hh:mm */
1426
0
  if (tz_length == 6 && tz_start[3] == ':')
1427
0
    {
1428
0
      if (!get_iso8601_int (tz_start + 1, 2, &offset_hours) ||
1429
0
          !get_iso8601_int (tz_start + 4, 2, &offset_minutes))
1430
0
        return NULL;
1431
0
    }
1432
  /* +hhmm or -hhmm */
1433
0
  else if (tz_length == 5)
1434
0
    {
1435
0
      if (!get_iso8601_int (tz_start + 1, 2, &offset_hours) ||
1436
0
          !get_iso8601_int (tz_start + 3, 2, &offset_minutes))
1437
0
        return NULL;
1438
0
    }
1439
  /* +hh or -hh */
1440
0
  else if (tz_length == 3)
1441
0
    {
1442
0
      if (!get_iso8601_int (tz_start + 1, 2, &offset_hours))
1443
0
        return NULL;
1444
0
      offset_minutes = 0;
1445
0
    }
1446
0
  else
1447
0
    return NULL;
1448
1449
0
  *tz_offset = tz_start - text;
1450
0
  tz = g_time_zone_new_identifier (tz_start);
1451
1452
  /* Double-check that the GTimeZone matches our interpretation of the timezone.
1453
   * This can fail because our interpretation is less strict than (for example)
1454
   * parse_time() in gtimezone.c, which restricts the range of the parsed
1455
   * integers. */
1456
0
  if (tz == NULL || g_time_zone_get_offset (tz, 0) != offset_sign * (offset_hours * 3600 + offset_minutes * 60))
1457
0
    {
1458
0
      g_clear_pointer (&tz, g_time_zone_unref);
1459
0
      return NULL;
1460
0
    }
1461
1462
0
  return tz;
1463
0
}
1464
1465
static gboolean
1466
parse_iso8601_time (const gchar *text, gsize length,
1467
                    gint *hour, gint *minute, gdouble *seconds, GTimeZone **tz)
1468
0
{
1469
0
  size_t tz_offset = 0;
1470
1471
  /* Check for timezone suffix */
1472
0
  *tz = parse_iso8601_timezone (text, length, &tz_offset);
1473
0
  if (*tz != NULL)
1474
0
    length = tz_offset;
1475
1476
  /* hh:mm:ss(.sss) */
1477
0
  if (length >= 8 && text[2] == ':' && text[5] == ':')
1478
0
    {
1479
0
      return get_iso8601_int (text, 2, hour) &&
1480
0
             get_iso8601_int (text + 3, 2, minute) &&
1481
0
             get_iso8601_seconds (text + 6, length - 6, seconds);
1482
0
    }
1483
  /* hhmmss(.sss) */
1484
0
  else if (length >= 6)
1485
0
    {
1486
0
      return get_iso8601_int (text, 2, hour) &&
1487
0
             get_iso8601_int (text + 2, 2, minute) &&
1488
0
             get_iso8601_seconds (text + 4, length - 4, seconds);
1489
0
    }
1490
0
  else
1491
0
    return FALSE;
1492
0
}
1493
1494
/**
1495
 * g_date_time_new_from_iso8601: (constructor)
1496
 * @text: an ISO 8601 formatted time string.
1497
 * @default_tz: (nullable): a #GTimeZone to use if the text doesn't contain a
1498
 *                          timezone, or %NULL.
1499
 *
1500
 * Creates a #GDateTime corresponding to the given
1501
 * [ISO 8601 formatted string](https://en.wikipedia.org/wiki/ISO_8601)
1502
 * @text. ISO 8601 strings of the form `<date><sep><time><tz>` are supported, with
1503
 * some extensions from [RFC 3339](https://tools.ietf.org/html/rfc3339) as
1504
 * mentioned below.
1505
 *
1506
 * Note that as #GDateTime "is oblivious to leap seconds", leap seconds information
1507
 * in an ISO-8601 string will be ignored, so a `23:59:60` time would be parsed as
1508
 * `23:59:59`.
1509
 *
1510
 * `<sep>` is the separator and can be either 'T', 't' or ' '. The latter two
1511
 * separators are an extension from
1512
 * [RFC 3339](https://tools.ietf.org/html/rfc3339#section-5.6).
1513
 *
1514
 * `<date>` is in the form:
1515
 *
1516
 * - `YYYY-MM-DD` - Year/month/day, e.g. 2016-08-24.
1517
 * - `YYYYMMDD` - Same as above without dividers.
1518
 * - `YYYY-DDD` - Ordinal day where DDD is from 001 to 366, e.g. 2016-237.
1519
 * - `YYYYDDD` - Same as above without dividers.
1520
 * - `YYYY-Www-D` - Week day where ww is from 01 to 52 and D from 1-7,
1521
 *   e.g. 2016-W34-3.
1522
 * - `YYYYWwwD` - Same as above without dividers.
1523
 *
1524
 * `<time>` is in the form:
1525
 *
1526
 * - `hh:mm:ss(.sss)` - Hours, minutes, seconds (subseconds), e.g. 22:10:42.123.
1527
 * - `hhmmss(.sss)` - Same as above without dividers.
1528
 *
1529
 * `<tz>` is an optional timezone suffix of the form:
1530
 *
1531
 * - `Z` - UTC.
1532
 * - `+hh:mm` or `-hh:mm` - Offset from UTC in hours and minutes, e.g. +12:00.
1533
 * - `+hh` or `-hh` - Offset from UTC in hours, e.g. +12.
1534
 *
1535
 * If the timezone is not provided in @text it must be provided in @default_tz
1536
 * (this field is otherwise ignored).
1537
 *
1538
 * This call can fail (returning %NULL) if @text is not a valid ISO 8601
1539
 * formatted string.
1540
 *
1541
 * You should release the return value by calling g_date_time_unref()
1542
 * when you are done with it.
1543
 *
1544
 * Returns: (transfer full) (nullable): a new #GDateTime, or %NULL
1545
 *
1546
 * Since: 2.56
1547
 */
1548
GDateTime *
1549
g_date_time_new_from_iso8601 (const gchar *text, GTimeZone *default_tz)
1550
0
{
1551
0
  size_t length, date_length = 0;
1552
0
  gboolean date_length_set = FALSE;
1553
0
  gint hour = 0, minute = 0;
1554
0
  gdouble seconds = 0.0;
1555
0
  GTimeZone *tz = NULL;
1556
0
  GDateTime *datetime = NULL;
1557
1558
0
  g_return_val_if_fail (text != NULL, NULL);
1559
1560
  /* Count length of string and find date / time separator ('T', 't', or ' ') */
1561
0
  for (length = 0; text[length] != '\0'; length++)
1562
0
    {
1563
0
      if (!date_length_set && (text[length] == 'T' || text[length] == 't' || text[length] == ' '))
1564
0
        {
1565
0
          date_length = length;
1566
0
          date_length_set = TRUE;
1567
0
        }
1568
0
    }
1569
1570
0
  if (!date_length_set)
1571
0
    return NULL;
1572
1573
0
  if (!parse_iso8601_time (text + date_length + 1, length - (date_length + 1),
1574
0
                           &hour, &minute, &seconds, &tz))
1575
0
    goto out;
1576
0
  if (tz == NULL && default_tz == NULL)
1577
0
    return NULL;
1578
1579
0
  datetime = parse_iso8601_date (text, date_length, hour, minute, seconds, tz ? tz : default_tz);
1580
1581
0
out:
1582
0
    if (tz != NULL)
1583
0
      g_time_zone_unref (tz);
1584
0
    return datetime;
1585
0
}
1586
1587
/* full new functions {{{1 */
1588
1589
/**
1590
 * g_date_time_new: (constructor)
1591
 * @tz: a #GTimeZone
1592
 * @year: the year component of the date
1593
 * @month: the month component of the date
1594
 * @day: the day component of the date
1595
 * @hour: the hour component of the date
1596
 * @minute: the minute component of the date
1597
 * @seconds: the number of seconds past the minute
1598
 *
1599
 * Creates a new #GDateTime corresponding to the given date and time in
1600
 * the time zone @tz.
1601
 *
1602
 * The @year must be between 1 and 9999, @month between 1 and 12 and @day
1603
 * between 1 and 28, 29, 30 or 31 depending on the month and the year.
1604
 *
1605
 * @hour must be between 0 and 23 and @minute must be between 0 and 59.
1606
 *
1607
 * @seconds must be at least 0.0 and must be strictly less than 60.0.
1608
 * It will be rounded down to the nearest microsecond.
1609
 *
1610
 * If the given time is not representable in the given time zone (for
1611
 * example, 02:30 on March 14th 2010 in Toronto, due to daylight savings
1612
 * time) then the time will be rounded up to the nearest existing time
1613
 * (in this case, 03:00).  If this matters to you then you should verify
1614
 * the return value for containing the same as the numbers you gave.
1615
 *
1616
 * In the case that the given time is ambiguous in the given time zone
1617
 * (for example, 01:30 on November 7th 2010 in Toronto, due to daylight
1618
 * savings time) then the time falling within standard (ie:
1619
 * non-daylight) time is taken.
1620
 *
1621
 * It not considered a programmer error for the values to this function
1622
 * to be out of range, but in the case that they are, the function will
1623
 * return %NULL.
1624
 *
1625
 * You should release the return value by calling g_date_time_unref()
1626
 * when you are done with it.
1627
 *
1628
 * Returns: (transfer full) (nullable): a new #GDateTime, or %NULL
1629
 *
1630
 * Since: 2.26
1631
 **/
1632
GDateTime *
1633
g_date_time_new (GTimeZone *tz,
1634
                 gint       year,
1635
                 gint       month,
1636
                 gint       day,
1637
                 gint       hour,
1638
                 gint       minute,
1639
                 gdouble    seconds)
1640
0
{
1641
0
  GDateTime *datetime;
1642
0
  gint64 full_time;
1643
  /* keep these variables as volatile. We do not want them ending up in
1644
   * registers - them doing so may cause us to hit precision problems on i386.
1645
   * See: https://bugzilla.gnome.org/show_bug.cgi?id=792410 */
1646
0
  volatile gint64 usec;
1647
0
  volatile gdouble usecd;
1648
1649
0
  g_return_val_if_fail (tz != NULL, NULL);
1650
1651
0
  if (year < 1 || year > 9999 ||
1652
0
      month < 1 || month > 12 ||
1653
0
      day < 1 || day > days_in_months[GREGORIAN_LEAP (year)][month] ||
1654
0
      hour < 0 || hour > 23 ||
1655
0
      minute < 0 || minute > 59 ||
1656
0
      g_isnan (seconds) ||
1657
0
      seconds < 0.0 || seconds >= 60.0)
1658
0
    return NULL;
1659
1660
0
  datetime = g_date_time_alloc (tz);
1661
0
  datetime->days = ymd_to_days (year, month, day);
1662
0
  datetime->usec = (hour   * USEC_PER_HOUR)
1663
0
                 + (minute * USEC_PER_MINUTE)
1664
0
                 + (gint64) (seconds * USEC_PER_SECOND);
1665
1666
0
  full_time = SEC_PER_DAY *
1667
0
                (ymd_to_days (year, month, day) - UNIX_EPOCH_START) +
1668
0
              SECS_PER_HOUR * hour +
1669
0
              SECS_PER_MINUTE * minute +
1670
0
              (int) seconds;
1671
1672
0
  datetime->interval = g_time_zone_adjust_time (datetime->tz,
1673
0
                                                G_TIME_TYPE_STANDARD,
1674
0
                                                &full_time);
1675
1676
  /* This is the correct way to convert a scaled FP value to integer.
1677
   * If this surprises you, please observe that (int)(1.000001 * 1e6)
1678
   * is 1000000.  This is not a problem with precision, it's just how
1679
   * FP numbers work.
1680
   * See https://bugzilla.gnome.org/show_bug.cgi?id=697715. */
1681
0
  usec = (gint64) (seconds * USEC_PER_SECOND);
1682
0
  usecd = (usec + 1) * 1e-6;
1683
0
  if (usecd <= seconds) {
1684
0
    usec++;
1685
0
  }
1686
1687
0
  full_time += UNIX_EPOCH_START * SEC_PER_DAY;
1688
0
  datetime->days = full_time / SEC_PER_DAY;
1689
0
  datetime->usec = (full_time % SEC_PER_DAY) * USEC_PER_SECOND;
1690
0
  datetime->usec += usec % USEC_PER_SECOND;
1691
1692
0
  return datetime;
1693
0
}
1694
1695
/**
1696
 * g_date_time_new_local: (constructor)
1697
 * @year: the year component of the date
1698
 * @month: the month component of the date
1699
 * @day: the day component of the date
1700
 * @hour: the hour component of the date
1701
 * @minute: the minute component of the date
1702
 * @seconds: the number of seconds past the minute
1703
 *
1704
 * Creates a new #GDateTime corresponding to the given date and time in
1705
 * the local time zone.
1706
 *
1707
 * This call is equivalent to calling g_date_time_new() with the time
1708
 * zone returned by g_time_zone_new_local().
1709
 *
1710
 * Returns: (transfer full) (nullable): a #GDateTime, or %NULL
1711
 *
1712
 * Since: 2.26
1713
 **/
1714
GDateTime *
1715
g_date_time_new_local (gint    year,
1716
                       gint    month,
1717
                       gint    day,
1718
                       gint    hour,
1719
                       gint    minute,
1720
                       gdouble seconds)
1721
0
{
1722
0
  GDateTime *datetime;
1723
0
  GTimeZone *local;
1724
1725
0
  local = g_time_zone_new_local ();
1726
0
  datetime = g_date_time_new (local, year, month, day, hour, minute, seconds);
1727
0
  g_time_zone_unref (local);
1728
1729
0
  return datetime;
1730
0
}
1731
1732
/**
1733
 * g_date_time_new_utc: (constructor)
1734
 * @year: the year component of the date
1735
 * @month: the month component of the date
1736
 * @day: the day component of the date
1737
 * @hour: the hour component of the date
1738
 * @minute: the minute component of the date
1739
 * @seconds: the number of seconds past the minute
1740
 *
1741
 * Creates a new #GDateTime corresponding to the given date and time in
1742
 * UTC.
1743
 *
1744
 * This call is equivalent to calling g_date_time_new() with the time
1745
 * zone returned by g_time_zone_new_utc().
1746
 *
1747
 * Returns: (transfer full) (nullable): a #GDateTime, or %NULL
1748
 *
1749
 * Since: 2.26
1750
 **/
1751
GDateTime *
1752
g_date_time_new_utc (gint    year,
1753
                     gint    month,
1754
                     gint    day,
1755
                     gint    hour,
1756
                     gint    minute,
1757
                     gdouble seconds)
1758
0
{
1759
0
  GDateTime *datetime;
1760
0
  GTimeZone *utc;
1761
1762
0
  utc = g_time_zone_new_utc ();
1763
0
  datetime = g_date_time_new (utc, year, month, day, hour, minute, seconds);
1764
0
  g_time_zone_unref (utc);
1765
1766
0
  return datetime;
1767
0
}
1768
1769
/* Adders {{{1 */
1770
1771
/**
1772
 * g_date_time_add:
1773
 * @datetime: a #GDateTime
1774
 * @timespan: a #GTimeSpan
1775
 *
1776
 * Creates a copy of @datetime and adds the specified timespan to the copy.
1777
 *
1778
 * Returns: (transfer full) (nullable): the newly created #GDateTime which
1779
 *   should be freed with g_date_time_unref(), or %NULL
1780
 *
1781
 * Since: 2.26
1782
 */
1783
GDateTime*
1784
g_date_time_add (GDateTime *datetime,
1785
                 GTimeSpan  timespan)
1786
0
{
1787
0
  g_return_val_if_fail (datetime != NULL, NULL);
1788
1789
0
  return g_date_time_from_instant (datetime->tz, timespan +
1790
0
                                   g_date_time_to_instant (datetime));
1791
0
}
1792
1793
/**
1794
 * g_date_time_add_years:
1795
 * @datetime: a #GDateTime
1796
 * @years: the number of years
1797
 *
1798
 * Creates a copy of @datetime and adds the specified number of years to the
1799
 * copy. Add negative values to subtract years.
1800
 *
1801
 * As with g_date_time_add_months(), if the resulting date would be 29th
1802
 * February on a non-leap year, the day will be clamped to 28th February.
1803
 *
1804
 * Returns: (transfer full) (nullable): the newly created #GDateTime which
1805
 *   should be freed with g_date_time_unref(), or %NULL
1806
 *
1807
 * Since: 2.26
1808
 */
1809
GDateTime *
1810
g_date_time_add_years (GDateTime *datetime,
1811
                       gint       years)
1812
0
{
1813
0
  gint year, month, day;
1814
1815
0
  g_return_val_if_fail (datetime != NULL, NULL);
1816
1817
0
  if (years < -10000 || years > 10000)
1818
0
    return NULL;
1819
1820
0
  g_date_time_get_ymd (datetime, &year, &month, &day);
1821
0
  year += years;
1822
1823
  /* only possible issue is if we've entered a year with no February 29
1824
   */
1825
0
  if (month == 2 && day == 29 && !GREGORIAN_LEAP (year))
1826
0
    day = 28;
1827
1828
0
  return g_date_time_replace_days (datetime, ymd_to_days (year, month, day));
1829
0
}
1830
1831
/**
1832
 * g_date_time_add_months:
1833
 * @datetime: a #GDateTime
1834
 * @months: the number of months
1835
 *
1836
 * Creates a copy of @datetime and adds the specified number of months to the
1837
 * copy. Add negative values to subtract months.
1838
 *
1839
 * The day of the month of the resulting #GDateTime is clamped to the number
1840
 * of days in the updated calendar month. For example, if adding 1 month to
1841
 * 31st January 2018, the result would be 28th February 2018. In 2020 (a leap
1842
 * year), the result would be 29th February.
1843
 *
1844
 * Returns: (transfer full) (nullable): the newly created #GDateTime which
1845
 *   should be freed with g_date_time_unref(), or %NULL
1846
 *
1847
 * Since: 2.26
1848
 */
1849
GDateTime*
1850
g_date_time_add_months (GDateTime *datetime,
1851
                        gint       months)
1852
0
{
1853
0
  gint year, month, day;
1854
1855
0
  g_return_val_if_fail (datetime != NULL, NULL);
1856
0
  g_date_time_get_ymd (datetime, &year, &month, &day);
1857
1858
0
  if (months < -120000 || months > 120000)
1859
0
    return NULL;
1860
1861
0
  year += months / 12;
1862
0
  month += months % 12;
1863
0
  if (month < 1)
1864
0
    {
1865
0
      month += 12;
1866
0
      year--;
1867
0
    }
1868
0
  else if (month > 12)
1869
0
    {
1870
0
      month -= 12;
1871
0
      year++;
1872
0
    }
1873
1874
0
  day = MIN (day, days_in_months[GREGORIAN_LEAP (year)][month]);
1875
1876
0
  return g_date_time_replace_days (datetime, ymd_to_days (year, month, day));
1877
0
}
1878
1879
/**
1880
 * g_date_time_add_weeks:
1881
 * @datetime: a #GDateTime
1882
 * @weeks: the number of weeks
1883
 *
1884
 * Creates a copy of @datetime and adds the specified number of weeks to the
1885
 * copy. Add negative values to subtract weeks.
1886
 *
1887
 * Returns: (transfer full) (nullable): the newly created #GDateTime which
1888
 *   should be freed with g_date_time_unref(), or %NULL
1889
 *
1890
 * Since: 2.26
1891
 */
1892
GDateTime*
1893
g_date_time_add_weeks (GDateTime *datetime,
1894
                       gint             weeks)
1895
0
{
1896
0
  g_return_val_if_fail (datetime != NULL, NULL);
1897
1898
0
  return g_date_time_add_days (datetime, weeks * 7);
1899
0
}
1900
1901
/**
1902
 * g_date_time_add_days:
1903
 * @datetime: a #GDateTime
1904
 * @days: the number of days
1905
 *
1906
 * Creates a copy of @datetime and adds the specified number of days to the
1907
 * copy. Add negative values to subtract days.
1908
 *
1909
 * Returns: (transfer full) (nullable): the newly created #GDateTime which
1910
 *   should be freed with g_date_time_unref(), or %NULL
1911
 *
1912
 * Since: 2.26
1913
 */
1914
GDateTime*
1915
g_date_time_add_days (GDateTime *datetime,
1916
                      gint       days)
1917
0
{
1918
0
  g_return_val_if_fail (datetime != NULL, NULL);
1919
1920
0
  if (days < -3660000 || days > 3660000)
1921
0
    return NULL;
1922
1923
0
  return g_date_time_replace_days (datetime, datetime->days + days);
1924
0
}
1925
1926
/**
1927
 * g_date_time_add_hours:
1928
 * @datetime: a #GDateTime
1929
 * @hours: the number of hours to add
1930
 *
1931
 * Creates a copy of @datetime and adds the specified number of hours.
1932
 * Add negative values to subtract hours.
1933
 *
1934
 * Returns: (transfer full) (nullable): the newly created #GDateTime which
1935
 *   should be freed with g_date_time_unref(), or %NULL
1936
 *
1937
 * Since: 2.26
1938
 */
1939
GDateTime*
1940
g_date_time_add_hours (GDateTime *datetime,
1941
                       gint       hours)
1942
0
{
1943
0
  return g_date_time_add (datetime, hours * USEC_PER_HOUR);
1944
0
}
1945
1946
/**
1947
 * g_date_time_add_minutes:
1948
 * @datetime: a #GDateTime
1949
 * @minutes: the number of minutes to add
1950
 *
1951
 * Creates a copy of @datetime adding the specified number of minutes.
1952
 * Add negative values to subtract minutes.
1953
 *
1954
 * Returns: (transfer full) (nullable): the newly created #GDateTime which
1955
 *   should be freed with g_date_time_unref(), or %NULL
1956
 *
1957
 * Since: 2.26
1958
 */
1959
GDateTime*
1960
g_date_time_add_minutes (GDateTime *datetime,
1961
                         gint             minutes)
1962
0
{
1963
0
  return g_date_time_add (datetime, minutes * USEC_PER_MINUTE);
1964
0
}
1965
1966
1967
/**
1968
 * g_date_time_add_seconds:
1969
 * @datetime: a #GDateTime
1970
 * @seconds: the number of seconds to add
1971
 *
1972
 * Creates a copy of @datetime and adds the specified number of seconds.
1973
 * Add negative values to subtract seconds.
1974
 *
1975
 * Returns: (transfer full) (nullable): the newly created #GDateTime which
1976
 *   should be freed with g_date_time_unref(), or %NULL
1977
 *
1978
 * Since: 2.26
1979
 */
1980
GDateTime*
1981
g_date_time_add_seconds (GDateTime *datetime,
1982
                         gdouble    seconds)
1983
0
{
1984
0
  return g_date_time_add (datetime, (GTimeSpan) (seconds * USEC_PER_SECOND));
1985
0
}
1986
1987
/**
1988
 * g_date_time_add_full:
1989
 * @datetime: a #GDateTime
1990
 * @years: the number of years to add
1991
 * @months: the number of months to add
1992
 * @days: the number of days to add
1993
 * @hours: the number of hours to add
1994
 * @minutes: the number of minutes to add
1995
 * @seconds: the number of seconds to add
1996
 *
1997
 * Creates a new #GDateTime adding the specified values to the current date and
1998
 * time in @datetime. Add negative values to subtract.
1999
 *
2000
 * Returns: (transfer full) (nullable): the newly created #GDateTime which
2001
 *   should be freed with g_date_time_unref(), or %NULL
2002
 *
2003
 * Since: 2.26
2004
 */
2005
GDateTime *
2006
g_date_time_add_full (GDateTime *datetime,
2007
                      gint       years,
2008
                      gint       months,
2009
                      gint       days,
2010
                      gint       hours,
2011
                      gint       minutes,
2012
                      gdouble    seconds)
2013
0
{
2014
0
  gint year, month, day;
2015
0
  gint64 full_time;
2016
0
  GDateTime *new;
2017
0
  gint interval;
2018
2019
0
  g_return_val_if_fail (datetime != NULL, NULL);
2020
0
  g_date_time_get_ymd (datetime, &year, &month, &day);
2021
2022
0
  months += years * 12;
2023
2024
0
  if (months < -120000 || months > 120000)
2025
0
    return NULL;
2026
2027
0
  if (days < -3660000 || days > 3660000)
2028
0
    return NULL;
2029
2030
0
  year += months / 12;
2031
0
  month += months % 12;
2032
0
  if (month < 1)
2033
0
    {
2034
0
      month += 12;
2035
0
      year--;
2036
0
    }
2037
0
  else if (month > 12)
2038
0
    {
2039
0
      month -= 12;
2040
0
      year++;
2041
0
    }
2042
2043
0
  day = MIN (day, days_in_months[GREGORIAN_LEAP (year)][month]);
2044
2045
  /* full_time is now in unix (local) time */
2046
0
  full_time = datetime->usec / USEC_PER_SECOND + SEC_PER_DAY *
2047
0
    (ymd_to_days (year, month, day) + days - UNIX_EPOCH_START);
2048
2049
0
  interval = g_time_zone_adjust_time (datetime->tz,
2050
0
                                      g_time_zone_is_dst (datetime->tz,
2051
0
                                                          datetime->interval),
2052
0
                                      &full_time);
2053
2054
  /* move to UTC unix time */
2055
0
  full_time -= g_time_zone_get_offset (datetime->tz, interval);
2056
2057
  /* convert back to an instant, add back fractional seconds */
2058
0
  full_time += UNIX_EPOCH_START * SEC_PER_DAY;
2059
0
  full_time = full_time * USEC_PER_SECOND +
2060
0
              datetime->usec % USEC_PER_SECOND;
2061
2062
  /* do the actual addition now */
2063
0
  full_time += (hours * USEC_PER_HOUR) +
2064
0
               (minutes * USEC_PER_MINUTE) +
2065
0
               (gint64) (seconds * USEC_PER_SECOND);
2066
2067
  /* find the new interval */
2068
0
  interval = g_time_zone_find_interval (datetime->tz,
2069
0
                                        G_TIME_TYPE_UNIVERSAL,
2070
0
                                        INSTANT_TO_UNIX (full_time));
2071
2072
  /* convert back into local time */
2073
0
  full_time += USEC_PER_SECOND *
2074
0
               g_time_zone_get_offset (datetime->tz, interval);
2075
2076
  /* split into days and usec of a new datetime */
2077
0
  new = g_date_time_alloc (datetime->tz);
2078
0
  new->interval = interval;
2079
0
  new->days = full_time / USEC_PER_DAY;
2080
0
  new->usec = full_time % USEC_PER_DAY;
2081
2082
  /* Validate it’s still in the range 0001-01-01 to 9999-12-31 */
2083
0
  if (new->days < MIN_DAYS || new->days > MAX_DAYS)
2084
0
    g_clear_pointer (&new, g_date_time_unref);
2085
2086
0
  return new;
2087
0
}
2088
2089
/* Compare, difference, hash, equal {{{1 */
2090
/**
2091
 * g_date_time_compare:
2092
 * @dt1: (type GDateTime) (not nullable): first date-time to compare
2093
 * @dt2: (type GDateTime) (not nullable): second date-time to compare
2094
 *
2095
 * A comparison function for date-times that is suitable
2096
 * as a [type@GLib.CompareFunc].
2097
 *
2098
 * This effectively converts both date-times to the same time zone before
2099
 * comparing, so date-times in different time zones can compare equal if they
2100
 * refer to the same instant. See [method@GLib.DateTime.difference].
2101
 *
2102
 * Both date-times must be non-`NULL`.
2103
 *
2104
 * Returns: `-1`, `0` or `1` if @dt1 is less than, equal to or greater than @dt2
2105
 * Since: 2.26
2106
 */
2107
gint
2108
g_date_time_compare (gconstpointer dt1,
2109
                     gconstpointer dt2)
2110
0
{
2111
0
  gint64 difference;
2112
2113
0
  difference = g_date_time_difference ((GDateTime *) dt1, (GDateTime *) dt2);
2114
2115
0
  if (difference < 0)
2116
0
    return -1;
2117
2118
0
  else if (difference > 0)
2119
0
    return 1;
2120
2121
0
  else
2122
0
    return 0;
2123
0
}
2124
2125
/**
2126
 * g_date_time_difference:
2127
 * @end: a date-time
2128
 * @begin: another date-time
2129
 *
2130
 * Calculates the difference in time between @end and @begin.
2131
 *
2132
 * The time span that is returned is effectively @end - @begin (positive if the
2133
 * first parameter is larger).
2134
 *
2135
 * This effectively converts both date-times to the same time zone before
2136
 * calculating the difference.
2137
 *
2138
 * Returns: the difference between the two date-times, as a time
2139
 *   span expressed in microseconds
2140
 * Since: 2.26
2141
 */
2142
GTimeSpan
2143
g_date_time_difference (GDateTime *end,
2144
                        GDateTime *begin)
2145
0
{
2146
0
  g_return_val_if_fail (begin != NULL, 0);
2147
0
  g_return_val_if_fail (end != NULL, 0);
2148
2149
0
  return g_date_time_to_instant (end) -
2150
0
         g_date_time_to_instant (begin);
2151
0
}
2152
2153
/**
2154
 * g_date_time_hash:
2155
 * @datetime: (type GDateTime) (not nullable): a #GDateTime
2156
 *
2157
 * Hashes @datetime into a #guint, suitable for use within #GHashTable.
2158
 *
2159
 * Returns: a #guint containing the hash
2160
 *
2161
 * Since: 2.26
2162
 */
2163
guint
2164
g_date_time_hash (gconstpointer datetime)
2165
0
{
2166
0
  g_return_val_if_fail (datetime != NULL, 0);
2167
2168
0
  return g_date_time_to_instant ((GDateTime *) datetime);
2169
0
}
2170
2171
/**
2172
 * g_date_time_equal:
2173
 * @dt1: (type GDateTime) (not nullable): a #GDateTime
2174
 * @dt2: (type GDateTime) (not nullable): a #GDateTime
2175
 *
2176
 * Checks to see if @dt1 and @dt2 are equal.
2177
 *
2178
 * Equal here means that they represent the same moment after converting
2179
 * them to the same time zone.
2180
 *
2181
 * If you need to check that the date-times are in the same time zone as well
2182
 * as referring to the same instant in time, additionally compare the values
2183
 * returned by [method@GLib.TimeZone.get_offset] for the time zones for the two
2184
 * date-times.
2185
 *
2186
 * Returns: %TRUE if @dt1 and @dt2 are equal
2187
 *
2188
 * Since: 2.26
2189
 */
2190
gboolean
2191
g_date_time_equal (gconstpointer dt1,
2192
                   gconstpointer dt2)
2193
0
{
2194
0
  return g_date_time_difference ((GDateTime *) dt1, (GDateTime *) dt2) == 0;
2195
0
}
2196
2197
/* Year, Month, Day Getters {{{1 */
2198
/**
2199
 * g_date_time_get_ymd:
2200
 * @datetime: a #GDateTime.
2201
 * @year: (out) (optional): the return location for the gregorian year, or %NULL.
2202
 * @month: (out) (optional): the return location for the month of the year, or %NULL.
2203
 * @day: (out) (optional): the return location for the day of the month, or %NULL.
2204
 *
2205
 * Retrieves the Gregorian day, month, and year of a given #GDateTime.
2206
 *
2207
 * Since: 2.26
2208
 **/
2209
void
2210
g_date_time_get_ymd (GDateTime *datetime,
2211
                     gint      *year,
2212
                     gint      *month,
2213
                     gint      *day)
2214
0
{
2215
0
  gint the_year;
2216
0
  gint the_month;
2217
0
  gint the_day;
2218
0
  gint remaining_days;
2219
0
  gint y100_cycles;
2220
0
  gint y4_cycles;
2221
0
  gint y1_cycles;
2222
0
  gint preceding;
2223
0
  gboolean leap;
2224
2225
0
  g_return_if_fail (datetime != NULL);
2226
2227
0
  remaining_days = datetime->days;
2228
2229
  /*
2230
   * We need to convert an offset in days to its year/month/day representation.
2231
   * Leap years makes this a little trickier than it should be, so we use
2232
   * 400, 100 and 4 years cycles here to get to the correct year.
2233
   */
2234
2235
  /* Our days offset starts sets 0001-01-01 as day 1, if it was day 0 our
2236
   * math would be simpler, so let's do it */
2237
0
  remaining_days--;
2238
2239
0
  the_year = (remaining_days / DAYS_IN_400YEARS) * 400 + 1;
2240
0
  remaining_days = remaining_days % DAYS_IN_400YEARS;
2241
2242
0
  y100_cycles = remaining_days / DAYS_IN_100YEARS;
2243
0
  remaining_days = remaining_days % DAYS_IN_100YEARS;
2244
0
  the_year += y100_cycles * 100;
2245
2246
0
  y4_cycles = remaining_days / DAYS_IN_4YEARS;
2247
0
  remaining_days = remaining_days % DAYS_IN_4YEARS;
2248
0
  the_year += y4_cycles * 4;
2249
2250
0
  y1_cycles = remaining_days / 365;
2251
0
  the_year += y1_cycles;
2252
0
  remaining_days = remaining_days % 365;
2253
2254
0
  if (y1_cycles == 4 || y100_cycles == 4) {
2255
0
    g_assert (remaining_days == 0);
2256
2257
    /* special case that indicates that the date is actually one year before,
2258
     * in the 31th of December */
2259
0
    the_year--;
2260
0
    the_month = 12;
2261
0
    the_day = 31;
2262
0
    goto end;
2263
0
  }
2264
2265
  /* now get the month and the day */
2266
0
  leap = y1_cycles == 3 && (y4_cycles != 24 || y100_cycles == 3);
2267
2268
0
  g_assert (leap == GREGORIAN_LEAP(the_year));
2269
2270
0
  the_month = (remaining_days + 50) >> 5;
2271
0
  preceding = (days_in_year[0][the_month - 1] + (the_month > 2 && leap));
2272
0
  if (preceding > remaining_days)
2273
0
    {
2274
      /* estimate is too large */
2275
0
      the_month -= 1;
2276
0
      preceding -= leap ? days_in_months[1][the_month]
2277
0
                        : days_in_months[0][the_month];
2278
0
    }
2279
2280
0
  remaining_days -= preceding;
2281
0
  g_assert(0 <= remaining_days);
2282
2283
0
  the_day = remaining_days + 1;
2284
2285
0
end:
2286
0
  if (year)
2287
0
    *year = the_year;
2288
0
  if (month)
2289
0
    *month = the_month;
2290
0
  if (day)
2291
0
    *day = the_day;
2292
0
}
2293
2294
/**
2295
 * g_date_time_get_year:
2296
 * @datetime: A #GDateTime
2297
 *
2298
 * Retrieves the year represented by @datetime in the Gregorian calendar.
2299
 *
2300
 * Returns: the year represented by @datetime
2301
 *
2302
 * Since: 2.26
2303
 */
2304
gint
2305
g_date_time_get_year (GDateTime *datetime)
2306
0
{
2307
0
  gint year;
2308
2309
0
  g_return_val_if_fail (datetime != NULL, 0);
2310
2311
0
  g_date_time_get_ymd (datetime, &year, NULL, NULL);
2312
2313
0
  return year;
2314
0
}
2315
2316
/**
2317
 * g_date_time_get_month:
2318
 * @datetime: a #GDateTime
2319
 *
2320
 * Retrieves the month of the year represented by @datetime in the Gregorian
2321
 * calendar.
2322
 *
2323
 * Returns: the month represented by @datetime
2324
 *
2325
 * Since: 2.26
2326
 */
2327
gint
2328
g_date_time_get_month (GDateTime *datetime)
2329
0
{
2330
0
  gint month;
2331
2332
0
  g_return_val_if_fail (datetime != NULL, 0);
2333
2334
0
  g_date_time_get_ymd (datetime, NULL, &month, NULL);
2335
2336
0
  return month;
2337
0
}
2338
2339
/**
2340
 * g_date_time_get_day_of_month:
2341
 * @datetime: a #GDateTime
2342
 *
2343
 * Retrieves the day of the month represented by @datetime in the gregorian
2344
 * calendar.
2345
 *
2346
 * Returns: the day of the month
2347
 *
2348
 * Since: 2.26
2349
 */
2350
gint
2351
g_date_time_get_day_of_month (GDateTime *datetime)
2352
0
{
2353
0
  gint           day_of_year,
2354
0
                 i;
2355
0
  guint          is_leap;
2356
0
  guint16        last = 0;
2357
2358
0
  g_return_val_if_fail (datetime != NULL, 0);
2359
2360
0
  is_leap = GREGORIAN_LEAP (g_date_time_get_year (datetime)) ? 1 : 0;
2361
0
  g_date_time_get_week_number (datetime, NULL, NULL, &day_of_year);
2362
2363
0
  for (i = 1; i <= 12; i++)
2364
0
    {
2365
0
      if (days_in_year[is_leap][i] >= day_of_year)
2366
0
        return day_of_year - last;
2367
0
      last = days_in_year[is_leap][i];
2368
0
    }
2369
2370
0
  g_warn_if_reached ();
2371
0
  return 0;
2372
0
}
2373
2374
/* Week of year / day of week getters {{{1 */
2375
/**
2376
 * g_date_time_get_week_numbering_year:
2377
 * @datetime: a #GDateTime
2378
 *
2379
 * Returns the ISO 8601 week-numbering year in which the week containing
2380
 * @datetime falls.
2381
 *
2382
 * This function, taken together with g_date_time_get_week_of_year() and
2383
 * g_date_time_get_day_of_week() can be used to determine the full ISO
2384
 * week date on which @datetime falls.
2385
 *
2386
 * This is usually equal to the normal Gregorian year (as returned by
2387
 * g_date_time_get_year()), except as detailed below:
2388
 *
2389
 * For Thursday, the week-numbering year is always equal to the usual
2390
 * calendar year.  For other days, the number is such that every day
2391
 * within a complete week (Monday to Sunday) is contained within the
2392
 * same week-numbering year.
2393
 *
2394
 * For Monday, Tuesday and Wednesday occurring near the end of the year,
2395
 * this may mean that the week-numbering year is one greater than the
2396
 * calendar year (so that these days have the same week-numbering year
2397
 * as the Thursday occurring early in the next year).
2398
 *
2399
 * For Friday, Saturday and Sunday occurring near the start of the year,
2400
 * this may mean that the week-numbering year is one less than the
2401
 * calendar year (so that these days have the same week-numbering year
2402
 * as the Thursday occurring late in the previous year).
2403
 *
2404
 * An equivalent description is that the week-numbering year is equal to
2405
 * the calendar year containing the majority of the days in the current
2406
 * week (Monday to Sunday).
2407
 *
2408
 * Note that January 1 0001 in the proleptic Gregorian calendar is a
2409
 * Monday, so this function never returns 0.
2410
 *
2411
 * Returns: the ISO 8601 week-numbering year for @datetime
2412
 *
2413
 * Since: 2.26
2414
 **/
2415
gint
2416
g_date_time_get_week_numbering_year (GDateTime *datetime)
2417
0
{
2418
0
  gint year = -1, month = -1, day = -1, weekday;
2419
2420
0
  g_date_time_get_ymd (datetime, &year, &month, &day);
2421
0
  weekday = g_date_time_get_day_of_week (datetime);
2422
2423
  /* January 1, 2, 3 might be in the previous year if they occur after
2424
   * Thursday.
2425
   *
2426
   *   Jan 1:  Friday, Saturday, Sunday    =>  day 1:  weekday 5, 6, 7
2427
   *   Jan 2:  Saturday, Sunday            =>  day 2:  weekday 6, 7
2428
   *   Jan 3:  Sunday                      =>  day 3:  weekday 7
2429
   *
2430
   * So we have a special case if (day - weekday) <= -4
2431
   */
2432
0
  if (month == 1 && (day - weekday) <= -4)
2433
0
    return year - 1;
2434
2435
  /* December 29, 30, 31 might be in the next year if they occur before
2436
   * Thursday.
2437
   *
2438
   *   Dec 31: Monday, Tuesday, Wednesday  =>  day 31: weekday 1, 2, 3
2439
   *   Dec 30: Monday, Tuesday             =>  day 30: weekday 1, 2
2440
   *   Dec 29: Monday                      =>  day 29: weekday 1
2441
   *
2442
   * So we have a special case if (day - weekday) >= 28
2443
   */
2444
0
  else if (month == 12 && (day - weekday) >= 28)
2445
0
    return year + 1;
2446
2447
0
  else
2448
0
    return year;
2449
0
}
2450
2451
/**
2452
 * g_date_time_get_week_of_year:
2453
 * @datetime: a #GDateTime
2454
 *
2455
 * Returns the ISO 8601 week number for the week containing @datetime.
2456
 * The ISO 8601 week number is the same for every day of the week (from
2457
 * Moday through Sunday).  That can produce some unusual results
2458
 * (described below).
2459
 *
2460
 * The first week of the year is week 1.  This is the week that contains
2461
 * the first Thursday of the year.  Equivalently, this is the first week
2462
 * that has more than 4 of its days falling within the calendar year.
2463
 *
2464
 * The value 0 is never returned by this function.  Days contained
2465
 * within a year but occurring before the first ISO 8601 week of that
2466
 * year are considered as being contained in the last week of the
2467
 * previous year.  Similarly, the final days of a calendar year may be
2468
 * considered as being part of the first ISO 8601 week of the next year
2469
 * if 4 or more days of that week are contained within the new year.
2470
 *
2471
 * Returns: the ISO 8601 week number for @datetime.
2472
 *
2473
 * Since: 2.26
2474
 */
2475
gint
2476
g_date_time_get_week_of_year (GDateTime *datetime)
2477
0
{
2478
0
  gint weeknum;
2479
2480
0
  g_return_val_if_fail (datetime != NULL, 0);
2481
2482
0
  g_date_time_get_week_number (datetime, &weeknum, NULL, NULL);
2483
2484
0
  return weeknum;
2485
0
}
2486
2487
/**
2488
 * g_date_time_get_day_of_week:
2489
 * @datetime: a #GDateTime
2490
 *
2491
 * Retrieves the ISO 8601 day of the week on which @datetime falls (1 is
2492
 * Monday, 2 is Tuesday... 7 is Sunday).
2493
 *
2494
 * Returns: the day of the week
2495
 *
2496
 * Since: 2.26
2497
 */
2498
gint
2499
g_date_time_get_day_of_week (GDateTime *datetime)
2500
0
{
2501
0
  g_return_val_if_fail (datetime != NULL, 0);
2502
2503
0
  return (datetime->days - 1) % 7 + 1;
2504
0
}
2505
2506
/* Day of year getter {{{1 */
2507
/**
2508
 * g_date_time_get_day_of_year:
2509
 * @datetime: a #GDateTime
2510
 *
2511
 * Retrieves the day of the year represented by @datetime in the Gregorian
2512
 * calendar.
2513
 *
2514
 * Returns: the day of the year
2515
 *
2516
 * Since: 2.26
2517
 */
2518
gint
2519
g_date_time_get_day_of_year (GDateTime *datetime)
2520
0
{
2521
0
  gint doy = 0;
2522
2523
0
  g_return_val_if_fail (datetime != NULL, 0);
2524
2525
0
  g_date_time_get_week_number (datetime, NULL, NULL, &doy);
2526
0
  return doy;
2527
0
}
2528
2529
/* Time component getters {{{1 */
2530
2531
/**
2532
 * g_date_time_get_hour:
2533
 * @datetime: a #GDateTime
2534
 *
2535
 * Retrieves the hour of the day represented by @datetime
2536
 *
2537
 * Returns: the hour of the day
2538
 *
2539
 * Since: 2.26
2540
 */
2541
gint
2542
g_date_time_get_hour (GDateTime *datetime)
2543
0
{
2544
0
  g_return_val_if_fail (datetime != NULL, 0);
2545
2546
0
  return (datetime->usec / USEC_PER_HOUR);
2547
0
}
2548
2549
/**
2550
 * g_date_time_get_minute:
2551
 * @datetime: a #GDateTime
2552
 *
2553
 * Retrieves the minute of the hour represented by @datetime
2554
 *
2555
 * Returns: the minute of the hour
2556
 *
2557
 * Since: 2.26
2558
 */
2559
gint
2560
g_date_time_get_minute (GDateTime *datetime)
2561
0
{
2562
0
  g_return_val_if_fail (datetime != NULL, 0);
2563
2564
0
  return (datetime->usec % USEC_PER_HOUR) / USEC_PER_MINUTE;
2565
0
}
2566
2567
/**
2568
 * g_date_time_get_second:
2569
 * @datetime: a #GDateTime
2570
 *
2571
 * Retrieves the second of the minute represented by @datetime
2572
 *
2573
 * Returns: the second represented by @datetime
2574
 *
2575
 * Since: 2.26
2576
 */
2577
gint
2578
g_date_time_get_second (GDateTime *datetime)
2579
0
{
2580
0
  g_return_val_if_fail (datetime != NULL, 0);
2581
2582
0
  return (datetime->usec % USEC_PER_MINUTE) / USEC_PER_SECOND;
2583
0
}
2584
2585
/**
2586
 * g_date_time_get_microsecond:
2587
 * @datetime: a #GDateTime
2588
 *
2589
 * Retrieves the microsecond of the date represented by @datetime
2590
 *
2591
 * Returns: the microsecond of the second
2592
 *
2593
 * Since: 2.26
2594
 */
2595
gint
2596
g_date_time_get_microsecond (GDateTime *datetime)
2597
0
{
2598
0
  g_return_val_if_fail (datetime != NULL, 0);
2599
2600
0
  return (datetime->usec % USEC_PER_SECOND);
2601
0
}
2602
2603
/**
2604
 * g_date_time_get_seconds:
2605
 * @datetime: a #GDateTime
2606
 *
2607
 * Retrieves the number of seconds since the start of the last minute,
2608
 * including the fractional part.
2609
 *
2610
 * Returns: the number of seconds
2611
 *
2612
 * Since: 2.26
2613
 **/
2614
gdouble
2615
g_date_time_get_seconds (GDateTime *datetime)
2616
0
{
2617
0
  g_return_val_if_fail (datetime != NULL, 0);
2618
2619
0
  return (datetime->usec % USEC_PER_MINUTE) / 1000000.0;
2620
0
}
2621
2622
/* Exporters {{{1 */
2623
/**
2624
 * g_date_time_to_unix:
2625
 * @datetime: a #GDateTime
2626
 *
2627
 * Gives the Unix time corresponding to @datetime, rounding down to the
2628
 * nearest second.
2629
 *
2630
 * Unix time is the number of seconds that have elapsed since 1970-01-01
2631
 * 00:00:00 UTC, regardless of the time zone associated with @datetime.
2632
 *
2633
 * Returns: the Unix time corresponding to @datetime
2634
 *
2635
 * Since: 2.26
2636
 **/
2637
gint64
2638
g_date_time_to_unix (GDateTime *datetime)
2639
0
{
2640
0
  g_return_val_if_fail (datetime != NULL, 0);
2641
2642
0
  return INSTANT_TO_UNIX (g_date_time_to_instant (datetime));
2643
0
}
2644
2645
/**
2646
 * g_date_time_to_unix_usec:
2647
 * @datetime: a #GDateTime
2648
 *
2649
 * Gives the Unix time corresponding to @datetime, in microseconds.
2650
 *
2651
 * Unix time is the number of microseconds that have elapsed since 1970-01-01
2652
 * 00:00:00 UTC, regardless of the time zone associated with @datetime.
2653
 *
2654
 * Returns: the Unix time corresponding to @datetime
2655
 *
2656
 * Since: 2.80
2657
 **/
2658
gint64
2659
g_date_time_to_unix_usec (GDateTime *datetime)
2660
0
{
2661
0
  g_return_val_if_fail (datetime != NULL, 0);
2662
2663
0
  return INSTANT_TO_UNIX_USECS (g_date_time_to_instant (datetime));
2664
0
}
2665
2666
/**
2667
 * g_date_time_to_timeval:
2668
 * @datetime: a #GDateTime
2669
 * @tv: a #GTimeVal to modify
2670
 *
2671
 * Stores the instant in time that @datetime represents into @tv.
2672
 *
2673
 * The time contained in a #GTimeVal is always stored in the form of
2674
 * seconds elapsed since 1970-01-01 00:00:00 UTC, regardless of the time
2675
 * zone associated with @datetime.
2676
 *
2677
 * On systems where 'long' is 32bit (ie: all 32bit systems and all
2678
 * Windows systems), a #GTimeVal is incapable of storing the entire
2679
 * range of values that #GDateTime is capable of expressing.  On those
2680
 * systems, this function returns %FALSE to indicate that the time is
2681
 * out of range.
2682
 *
2683
 * On systems where 'long' is 64bit, this function never fails.
2684
 *
2685
 * Returns: %TRUE if successful, else %FALSE
2686
 *
2687
 * Since: 2.26
2688
 * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use
2689
 *    g_date_time_to_unix() instead.
2690
 **/
2691
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
2692
gboolean
2693
g_date_time_to_timeval (GDateTime *datetime,
2694
                        GTimeVal  *tv)
2695
0
{
2696
0
  g_return_val_if_fail (datetime != NULL, FALSE);
2697
2698
0
  tv->tv_sec = INSTANT_TO_UNIX (g_date_time_to_instant (datetime));
2699
0
  tv->tv_usec = datetime->usec % USEC_PER_SECOND;
2700
2701
0
  return TRUE;
2702
0
}
2703
G_GNUC_END_IGNORE_DEPRECATIONS
2704
2705
/* Timezone queries {{{1 */
2706
/**
2707
 * g_date_time_get_utc_offset:
2708
 * @datetime: a #GDateTime
2709
 *
2710
 * Determines the offset to UTC in effect at the time and in the time
2711
 * zone of @datetime.
2712
 *
2713
 * The offset is the number of microseconds that you add to UTC time to
2714
 * arrive at local time for the time zone (ie: negative numbers for time
2715
 * zones west of GMT, positive numbers for east).
2716
 *
2717
 * If @datetime represents UTC time, then the offset is always zero.
2718
 *
2719
 * Returns: the number of microseconds that should be added to UTC to
2720
 *          get the local time
2721
 *
2722
 * Since: 2.26
2723
 **/
2724
GTimeSpan
2725
g_date_time_get_utc_offset (GDateTime *datetime)
2726
0
{
2727
0
  gint offset;
2728
2729
0
  g_return_val_if_fail (datetime != NULL, 0);
2730
2731
0
  offset = g_time_zone_get_offset (datetime->tz, datetime->interval);
2732
2733
0
  return (gint64) offset * USEC_PER_SECOND;
2734
0
}
2735
2736
/**
2737
 * g_date_time_get_timezone:
2738
 * @datetime: a #GDateTime
2739
 *
2740
 * Get the time zone for this @datetime.
2741
 *
2742
 * Returns: (transfer none): the time zone
2743
 * Since: 2.58
2744
 */
2745
GTimeZone *
2746
g_date_time_get_timezone (GDateTime *datetime)
2747
0
{
2748
0
  g_return_val_if_fail (datetime != NULL, NULL);
2749
2750
0
  g_assert (datetime->tz != NULL);
2751
0
  return datetime->tz;
2752
0
}
2753
2754
/**
2755
 * g_date_time_get_timezone_abbreviation:
2756
 * @datetime: a #GDateTime
2757
 *
2758
 * Determines the time zone abbreviation to be used at the time and in
2759
 * the time zone of @datetime.
2760
 *
2761
 * For example, in Toronto this is currently "EST" during the winter
2762
 * months and "EDT" during the summer months when daylight savings
2763
 * time is in effect.
2764
 *
2765
 * Returns: (transfer none): the time zone abbreviation. The returned
2766
 *          string is owned by the #GDateTime and it should not be
2767
 *          modified or freed
2768
 *
2769
 * Since: 2.26
2770
 **/
2771
const gchar *
2772
g_date_time_get_timezone_abbreviation (GDateTime *datetime)
2773
0
{
2774
0
  g_return_val_if_fail (datetime != NULL, NULL);
2775
2776
0
  return g_time_zone_get_abbreviation (datetime->tz, datetime->interval);
2777
0
}
2778
2779
/**
2780
 * g_date_time_is_daylight_savings:
2781
 * @datetime: a #GDateTime
2782
 *
2783
 * Determines if daylight savings time is in effect at the time and in
2784
 * the time zone of @datetime.
2785
 *
2786
 * Returns: %TRUE if daylight savings time is in effect
2787
 *
2788
 * Since: 2.26
2789
 **/
2790
gboolean
2791
g_date_time_is_daylight_savings (GDateTime *datetime)
2792
0
{
2793
0
  g_return_val_if_fail (datetime != NULL, FALSE);
2794
2795
0
  return g_time_zone_is_dst (datetime->tz, datetime->interval);
2796
0
}
2797
2798
/* Timezone convert {{{1 */
2799
/**
2800
 * g_date_time_to_timezone:
2801
 * @datetime: a #GDateTime
2802
 * @tz: the new #GTimeZone
2803
 *
2804
 * Create a new #GDateTime corresponding to the same instant in time as
2805
 * @datetime, but in the time zone @tz.
2806
 *
2807
 * This call can fail in the case that the time goes out of bounds.  For
2808
 * example, converting 0001-01-01 00:00:00 UTC to a time zone west of
2809
 * Greenwich will fail (due to the year 0 being out of range).
2810
 *
2811
 * Returns: (transfer full) (nullable): the newly created #GDateTime which
2812
 *   should be freed with g_date_time_unref(), or %NULL
2813
 *
2814
 * Since: 2.26
2815
 **/
2816
GDateTime *
2817
g_date_time_to_timezone (GDateTime *datetime,
2818
                         GTimeZone *tz)
2819
0
{
2820
0
  g_return_val_if_fail (datetime != NULL, NULL);
2821
0
  g_return_val_if_fail (tz != NULL, NULL);
2822
2823
0
  return g_date_time_from_instant (tz, g_date_time_to_instant (datetime));
2824
0
}
2825
2826
/**
2827
 * g_date_time_to_local:
2828
 * @datetime: a #GDateTime
2829
 *
2830
 * Creates a new #GDateTime corresponding to the same instant in time as
2831
 * @datetime, but in the local time zone.
2832
 *
2833
 * This call is equivalent to calling g_date_time_to_timezone() with the
2834
 * time zone returned by g_time_zone_new_local().
2835
 *
2836
 * Returns: (transfer full) (nullable): the newly created #GDateTime which
2837
 *   should be freed with g_date_time_unref(), or %NULL
2838
 *
2839
 * Since: 2.26
2840
 **/
2841
GDateTime *
2842
g_date_time_to_local (GDateTime *datetime)
2843
0
{
2844
0
  GDateTime *new;
2845
0
  GTimeZone *local;
2846
2847
0
  local = g_time_zone_new_local ();
2848
0
  new = g_date_time_to_timezone (datetime, local);
2849
0
  g_time_zone_unref (local);
2850
2851
0
  return new;
2852
0
}
2853
2854
/**
2855
 * g_date_time_to_utc:
2856
 * @datetime: a #GDateTime
2857
 *
2858
 * Creates a new #GDateTime corresponding to the same instant in time as
2859
 * @datetime, but in UTC.
2860
 *
2861
 * This call is equivalent to calling g_date_time_to_timezone() with the
2862
 * time zone returned by g_time_zone_new_utc().
2863
 *
2864
 * Returns: (transfer full) (nullable): the newly created #GDateTime which
2865
 *   should be freed with g_date_time_unref(), or %NULL
2866
 *
2867
 * Since: 2.26
2868
 **/
2869
GDateTime *
2870
g_date_time_to_utc (GDateTime *datetime)
2871
0
{
2872
0
  GDateTime *new;
2873
0
  GTimeZone *utc;
2874
2875
0
  utc = g_time_zone_new_utc ();
2876
0
  new = g_date_time_to_timezone (datetime, utc);
2877
0
  g_time_zone_unref (utc);
2878
2879
0
  return new;
2880
0
}
2881
2882
/* Format {{{1 */
2883
2884
static gboolean
2885
format_z (GString *outstr,
2886
          gint     offset,
2887
          guint    colons)
2888
0
{
2889
0
  gint hours;
2890
0
  gint minutes;
2891
0
  gint seconds;
2892
0
  gchar sign = offset >= 0 ? '+' : '-';
2893
2894
0
  offset = ABS (offset);
2895
0
  hours = offset / 3600;
2896
0
  minutes = offset / 60 % 60;
2897
0
  seconds = offset % 60;
2898
2899
0
  switch (colons)
2900
0
    {
2901
0
    case 0:
2902
0
      g_string_append_printf (outstr, "%c%02d%02d",
2903
0
                              sign,
2904
0
                              hours,
2905
0
                              minutes);
2906
0
      break;
2907
2908
0
    case 1:
2909
0
      g_string_append_printf (outstr, "%c%02d:%02d",
2910
0
                              sign,
2911
0
                              hours,
2912
0
                              minutes);
2913
0
      break;
2914
2915
0
    case 2:
2916
0
      g_string_append_printf (outstr, "%c%02d:%02d:%02d",
2917
0
                              sign,
2918
0
                              hours,
2919
0
                              minutes,
2920
0
                              seconds);
2921
0
      break;
2922
2923
0
    case 3:
2924
0
      g_string_append_printf (outstr, "%c%02d", sign, hours);
2925
2926
0
      if (minutes != 0 || seconds != 0)
2927
0
        {
2928
0
          g_string_append_printf (outstr, ":%02d", minutes);
2929
2930
0
          if (seconds != 0)
2931
0
            g_string_append_printf (outstr, ":%02d", seconds);
2932
0
        }
2933
0
      break;
2934
2935
0
    default:
2936
0
      return FALSE;
2937
0
    }
2938
2939
0
  return TRUE;
2940
0
}
2941
2942
#ifdef HAVE_LANGINFO_OUTDIGIT
2943
/* Initializes the array with UTF-8 encoded alternate digits suitable for use
2944
 * in current locale. Returns NULL when current locale does not use alternate
2945
 * digits or there was an error converting them to UTF-8.
2946
 *
2947
 * This needs external locking, so must only be called from within
2948
 * format_number().
2949
 */
2950
static const gchar * const *
2951
initialize_alt_digits (void)
2952
0
{
2953
0
  guint i;
2954
0
  gsize digit_len;
2955
0
  gchar *digit;
2956
0
  const gchar *locale_digit;
2957
0
#define N_DIGITS 10
2958
0
#define MAX_UTF8_ENCODING_LEN 4
2959
0
  static gchar buffer[N_DIGITS * (MAX_UTF8_ENCODING_LEN + 1 /* null separator */)];
2960
0
#undef N_DIGITS
2961
0
#undef MAX_UTF8_ENCODING_LEN
2962
0
  gchar *buffer_end = buffer;
2963
0
  static const gchar *alt_digits[10];
2964
2965
0
  for (i = 0; i != 10; ++i)
2966
0
    {
2967
0
      locale_digit = nl_langinfo (_NL_CTYPE_OUTDIGIT0_MB + i);
2968
2969
0
      if (g_strcmp0 (locale_digit, "") == 0)
2970
0
        return NULL;
2971
2972
0
      digit = _g_ctype_locale_to_utf8 (locale_digit, -1, NULL, &digit_len, NULL);
2973
0
      if (digit == NULL)
2974
0
        return NULL;
2975
2976
0
      g_assert (digit_len < (gsize) (buffer + sizeof (buffer) - buffer_end));
2977
2978
0
      alt_digits[i] = buffer_end;
2979
0
      buffer_end = g_stpcpy (buffer_end, digit);
2980
      /* skip trailing null byte */
2981
0
      buffer_end += 1;
2982
2983
0
      g_free (digit);
2984
0
    }
2985
2986
0
  return alt_digits;
2987
0
}
2988
#endif /* HAVE_LANGINFO_OUTDIGIT */
2989
2990
/* Look up the era which contains @datetime, in the ERA description from libc
2991
 * which corresponds to the currently set LC_TIME locale. The ERA is parsed and
2992
 * cached the first time this function is called (or when LC_TIME changes).
2993
 * See nl_langinfo(3).
2994
 *
2995
 * The return value is (transfer full). */
2996
static GEraDescriptionSegment *
2997
date_time_lookup_era (GDateTime *datetime,
2998
                      gboolean   locale_is_utf8)
2999
0
{
3000
0
  static GMutex era_mutex;
3001
0
  static GPtrArray *static_era_description = NULL;  /* (mutex era_mutex) (element-type GEraDescriptionSegment) */
3002
0
  static char *static_era_description_locale = NULL;  /* (mutex era_mutex) (owned) */
3003
0
  const char *current_lc_time = setlocale (LC_TIME, NULL);
3004
0
  GPtrArray *local_era_description;  /* (element-type GEraDescriptionSegment) */
3005
0
  GEraDate datetime_date;
3006
3007
0
  g_mutex_lock (&era_mutex);
3008
3009
0
  if (g_strcmp0 (static_era_description_locale, current_lc_time) != 0)
3010
0
    {
3011
0
      const char *era_description_str;
3012
0
      size_t era_description_str_len;
3013
0
      char *tmp = NULL;
3014
3015
0
      era_description_str = ERA_DESCRIPTION;
3016
0
      if (era_description_str != NULL)
3017
0
        {
3018
          /* FIXME: glibc 2.37 seems to return the era segments nul-separated rather
3019
           * than semicolon-separated (which is what nl_langinfo(3) specifies).
3020
           * Fix that up before sending it to the parsing code.
3021
           * See https://sourceware.org/bugzilla/show_bug.cgi?id=31030*/
3022
0
            {
3023
              /* Work out the length of the whole description string, regardless
3024
               * of whether it uses nuls or semicolons as separators. */
3025
0
              int n_entries = ERA_DESCRIPTION_N_SEGMENTS;
3026
0
              const char *s = era_description_str;
3027
0
              char *s2;
3028
3029
0
              for (int i = 1; i < n_entries; i++)
3030
0
                {
3031
0
                  const char *next_semicolon = strchr (s, ';');
3032
0
                  const char *next_nul = strchr (s, '\0');
3033
3034
0
                  if (next_semicolon != NULL && next_semicolon < next_nul)
3035
0
                    s = next_semicolon + 1;
3036
0
                  else
3037
0
                    s = next_nul + 1;
3038
0
                }
3039
3040
0
              era_description_str_len = strlen (s) + (s - era_description_str);
3041
3042
              /* Replace all the nuls with semicolons. */
3043
0
              s2 = tmp = g_memdup2 (era_description_str, era_description_str_len + 1);
3044
3045
0
              for (int i = 1; i < n_entries; i++)
3046
0
                {
3047
0
                  char *next_nul = strchr (s2, '\0');
3048
3049
0
                  if ((size_t) (next_nul - tmp) >= era_description_str_len)
3050
0
                    break;
3051
3052
0
                  *next_nul = ';';
3053
0
                  s2 = next_nul + 1;
3054
0
                }
3055
3056
0
              era_description_str = tmp;
3057
0
            }
3058
3059
          /* Convert from the LC_TIME encoding to UTF-8 if needed. */
3060
0
          if (!locale_is_utf8 && ERA_DESCRIPTION_IS_LOCALE)
3061
0
            {
3062
0
              char *tmp2 = NULL;
3063
0
              era_description_str = tmp2 = g_locale_to_utf8 (era_description_str, -1, NULL, NULL, NULL);
3064
0
              g_free (tmp);
3065
0
              tmp = g_steal_pointer (&tmp2);
3066
0
            }
3067
3068
0
          g_clear_pointer (&static_era_description, g_ptr_array_unref);
3069
3070
0
          if (era_description_str != NULL)
3071
0
            static_era_description = _g_era_description_parse (era_description_str);
3072
0
          if (static_era_description == NULL)
3073
0
            g_warning ("Could not parse ERA description: %s", era_description_str);
3074
0
        }
3075
0
      else
3076
0
        {
3077
0
          g_clear_pointer (&static_era_description, g_ptr_array_unref);
3078
0
        }
3079
3080
0
      g_free (tmp);
3081
3082
0
      g_free (static_era_description_locale);
3083
0
      static_era_description_locale = g_strdup (current_lc_time);
3084
0
      g_ignore_leak (static_era_description_locale);
3085
0
    }
3086
3087
0
  if (static_era_description == NULL)
3088
0
    {
3089
0
      g_mutex_unlock (&era_mutex);
3090
0
      return NULL;
3091
0
    }
3092
3093
0
  local_era_description = g_ptr_array_ref (static_era_description);
3094
0
  g_mutex_unlock (&era_mutex);
3095
3096
  /* Search through the eras and see if one matches. */
3097
0
  datetime_date.type = G_ERA_DATE_SET;
3098
0
  datetime_date.year = g_date_time_get_year (datetime);
3099
0
  datetime_date.month = g_date_time_get_month (datetime);
3100
0
  datetime_date.day = g_date_time_get_day_of_month (datetime);
3101
3102
0
  for (unsigned int i = 0; i < local_era_description->len; i++)
3103
0
    {
3104
0
      GEraDescriptionSegment *segment = g_ptr_array_index (local_era_description, i);
3105
3106
0
      if ((_g_era_date_compare (&segment->start_date, &datetime_date) <= 0 &&
3107
0
           _g_era_date_compare (&datetime_date, &segment->end_date) <= 0) ||
3108
0
          (_g_era_date_compare (&segment->end_date, &datetime_date) <= 0 &&
3109
0
           _g_era_date_compare (&datetime_date, &segment->start_date) <= 0))
3110
0
        {
3111
          /* @datetime is within this era segment. */
3112
0
          g_ptr_array_unref (local_era_description);
3113
0
          return _g_era_description_segment_ref (segment);
3114
0
        }
3115
0
    }
3116
3117
0
  g_ptr_array_unref (local_era_description);
3118
3119
0
  return NULL;
3120
0
}
3121
3122
static void
3123
format_number (GString     *str,
3124
               gboolean     use_alt_digits,
3125
               const gchar *pad,
3126
               gint         width,
3127
               guint32      number)
3128
0
{
3129
0
  const gchar *ascii_digits[10] = {
3130
0
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
3131
0
  };
3132
0
  const gchar * const *digits = ascii_digits;
3133
0
  const gchar *tmp[10] = { NULL, };
3134
0
  gint i = 0;
3135
0
#ifdef HAVE_LANGINFO_OUTDIGIT
3136
0
  static GMutex alt_digits_mutex;
3137
0
#endif
3138
3139
0
  g_return_if_fail (width <= 10);
3140
3141
0
#ifdef HAVE_LANGINFO_OUTDIGIT
3142
0
  if (use_alt_digits)
3143
0
    {
3144
0
      static const gchar * const *alt_digits = NULL;
3145
0
      static char *alt_digits_locale = NULL;
3146
0
      const char *current_ctype_locale = setlocale (LC_CTYPE, NULL);
3147
3148
      /* Lock so we can initialise (or re-initialise, if the locale has changed)
3149
       * and hold access to the digits buffer until done formatting. */
3150
0
      g_mutex_lock (&alt_digits_mutex);
3151
3152
0
      if (g_strcmp0 (alt_digits_locale, current_ctype_locale) != 0)
3153
0
        {
3154
0
          alt_digits = initialize_alt_digits ();
3155
3156
0
          if (alt_digits == NULL)
3157
0
            alt_digits = ascii_digits;
3158
3159
0
          g_free (alt_digits_locale);
3160
0
          alt_digits_locale = g_strdup (current_ctype_locale);
3161
0
        }
3162
3163
0
      digits = alt_digits;
3164
0
    }
3165
0
#endif /* HAVE_LANGINFO_OUTDIGIT */
3166
3167
0
  do
3168
0
    {
3169
0
      tmp[i++] = digits[number % 10];
3170
0
      number /= 10;
3171
0
    }
3172
0
  while (number);
3173
3174
0
  while (pad && i < width)
3175
0
    tmp[i++] = *pad == '0' ? digits[0] : pad;
3176
3177
0
#ifdef HAVE_LANGINFO_OUTDIGIT
3178
0
  if (use_alt_digits)
3179
0
    g_mutex_unlock (&alt_digits_mutex);
3180
0
#endif
3181
3182
  /* should really be impossible */
3183
0
  g_assert (i <= 10);
3184
3185
0
  while (i)
3186
0
    g_string_append (str, tmp[--i]);
3187
0
}
3188
3189
static gboolean
3190
format_ampm (GDateTime *datetime,
3191
             GString   *outstr,
3192
             gboolean   locale_is_utf8,
3193
             gboolean   uppercase)
3194
0
{
3195
0
  const gchar *ampm;
3196
0
  gchar       *tmp = NULL, *ampm_dup;
3197
3198
0
  ampm = GET_AMPM (datetime);
3199
3200
0
  if (!ampm || ampm[0] == '\0')
3201
0
    ampm = get_fallback_ampm (g_date_time_get_hour (datetime));
3202
3203
0
  if (!locale_is_utf8 && GET_AMPM_IS_LOCALE)
3204
0
    {
3205
      /* This assumes that locale encoding can't have embedded NULs */
3206
0
      ampm = tmp = g_locale_to_utf8 (ampm, -1, NULL, NULL, NULL);
3207
0
      if (tmp == NULL)
3208
0
        return FALSE;
3209
0
    }
3210
0
  if (uppercase)
3211
0
    ampm_dup = g_utf8_strup (ampm, -1);
3212
0
  else
3213
0
    ampm_dup = g_utf8_strdown (ampm, -1);
3214
0
  g_free (tmp);
3215
3216
0
  g_string_append (outstr, ampm_dup);
3217
0
  g_free (ampm_dup);
3218
3219
0
  return TRUE;
3220
0
}
3221
3222
static gboolean g_date_time_format_utf8 (GDateTime   *datetime,
3223
           const gchar *format,
3224
           GString     *outstr,
3225
           gboolean     locale_is_utf8);
3226
3227
/* g_date_time_format() subroutine that takes a locale-encoded format
3228
 * string and produces a UTF-8 encoded date/time string.
3229
 */
3230
static gboolean
3231
g_date_time_format_locale (GDateTime   *datetime,
3232
         const gchar *locale_format,
3233
         GString     *outstr,
3234
         gboolean     locale_is_utf8)
3235
0
{
3236
0
  gchar *utf8_format;
3237
0
  gboolean success;
3238
3239
0
  if (locale_is_utf8)
3240
0
    return g_date_time_format_utf8 (datetime, locale_format, outstr, locale_is_utf8);
3241
3242
0
  utf8_format = _g_time_locale_to_utf8 (locale_format, -1, NULL, NULL, NULL);
3243
0
  if (utf8_format == NULL)
3244
0
    return FALSE;
3245
3246
0
  success = g_date_time_format_utf8 (datetime, utf8_format, outstr,
3247
0
                                     locale_is_utf8);
3248
0
  g_free (utf8_format);
3249
0
  return success;
3250
0
}
3251
3252
static inline gboolean
3253
string_append (GString     *string,
3254
               const gchar *s,
3255
               gboolean     do_strup,
3256
               gboolean     s_is_utf8)
3257
0
{
3258
0
  gchar *utf8;
3259
0
  gsize  utf8_len;
3260
0
  char *tmp = NULL;
3261
3262
0
  if (s_is_utf8)
3263
0
    {
3264
0
      if (do_strup)
3265
0
        s = tmp = g_utf8_strup (s, -1);
3266
0
      g_string_append (string, s);
3267
0
    }
3268
0
  else
3269
0
    {
3270
0
      utf8 = _g_time_locale_to_utf8 (s, -1, NULL, &utf8_len, NULL);
3271
0
      if (utf8 == NULL)
3272
0
        return FALSE;
3273
0
      if (do_strup)
3274
0
        {
3275
0
          tmp = g_utf8_strup (utf8, utf8_len);
3276
0
          g_free (utf8);
3277
0
          utf8 = g_steal_pointer (&tmp);
3278
0
        }
3279
0
      g_string_append_len (string, utf8, utf8_len);
3280
0
      g_free (utf8);
3281
0
    }
3282
3283
0
  g_free (tmp);
3284
3285
0
  return TRUE;
3286
0
}
3287
3288
/* g_date_time_format() subroutine that takes a UTF-8 encoded format
3289
 * string and produces a UTF-8 encoded date/time string.
3290
 */
3291
static gboolean
3292
g_date_time_format_utf8 (GDateTime   *datetime,
3293
       const gchar *utf8_format,
3294
       GString     *outstr,
3295
       gboolean     locale_is_utf8)
3296
0
{
3297
0
  size_t len;
3298
0
  guint     colons;
3299
0
  gunichar  c;
3300
0
  gboolean  alt_digits = FALSE;
3301
0
  gboolean alt_era = FALSE;
3302
0
  gboolean  pad_set = FALSE;
3303
0
  gboolean mod_case = FALSE;
3304
0
  gboolean  name_is_utf8;
3305
0
  const gchar *pad = "";
3306
0
  const gchar *mod = "";
3307
0
  const gchar *name;
3308
0
  const gchar *tz;
3309
0
  char *tmp = NULL;
3310
3311
0
  while (*utf8_format)
3312
0
    {
3313
0
      len = strcspn (utf8_format, "%");
3314
0
      if (len)
3315
0
        g_string_append_len (outstr, utf8_format, len);
3316
3317
0
      utf8_format += len;
3318
0
      if (!*utf8_format)
3319
0
  break;
3320
3321
0
      g_assert (*utf8_format == '%');
3322
0
      utf8_format++;
3323
0
      if (!*utf8_format)
3324
0
  break;
3325
3326
0
      colons = 0;
3327
0
      alt_digits = FALSE;
3328
0
      alt_era = FALSE;
3329
0
      pad_set = FALSE;
3330
0
      mod_case = FALSE;
3331
3332
0
    next_mod:
3333
0
      c = g_utf8_get_char (utf8_format);
3334
0
      utf8_format = g_utf8_next_char (utf8_format);
3335
0
      switch (c)
3336
0
  {
3337
0
  case 'a':
3338
0
          name = WEEKDAY_ABBR (datetime);
3339
0
          if (g_strcmp0 (name, "") == 0)
3340
0
            return FALSE;
3341
3342
0
          name_is_utf8 = locale_is_utf8 || !WEEKDAY_ABBR_IS_LOCALE;
3343
3344
0
          if (!string_append (outstr, name, mod_case, name_is_utf8))
3345
0
            return FALSE;
3346
3347
0
    break;
3348
0
  case 'A':
3349
0
          name = WEEKDAY_FULL (datetime);
3350
0
          if (g_strcmp0 (name, "") == 0)
3351
0
            return FALSE;
3352
3353
0
          name_is_utf8 = locale_is_utf8 || !WEEKDAY_FULL_IS_LOCALE;
3354
3355
0
          if (!string_append (outstr, name, mod_case, name_is_utf8))
3356
0
            return FALSE;
3357
3358
0
    break;
3359
0
  case 'b':
3360
0
    name = alt_digits ? MONTH_ABBR_STANDALONE (datetime)
3361
0
          : MONTH_ABBR_WITH_DAY (datetime);
3362
0
          if (g_strcmp0 (name, "") == 0)
3363
0
            return FALSE;
3364
3365
0
          name_is_utf8 = locale_is_utf8 ||
3366
0
            ((alt_digits && !MONTH_ABBR_STANDALONE_IS_LOCALE) ||
3367
0
             (!alt_digits && !MONTH_ABBR_WITH_DAY_IS_LOCALE));
3368
3369
0
          if (!string_append (outstr, name, mod_case, name_is_utf8))
3370
0
            return FALSE;
3371
3372
0
    break;
3373
0
  case 'B':
3374
0
    name = alt_digits ? MONTH_FULL_STANDALONE (datetime)
3375
0
          : MONTH_FULL_WITH_DAY (datetime);
3376
0
          if (g_strcmp0 (name, "") == 0)
3377
0
            return FALSE;
3378
3379
0
          name_is_utf8 = locale_is_utf8 ||
3380
0
            ((alt_digits && !MONTH_FULL_STANDALONE_IS_LOCALE) ||
3381
0
             (!alt_digits && !MONTH_FULL_WITH_DAY_IS_LOCALE));
3382
3383
0
          if (!string_append (outstr, name, mod_case, name_is_utf8))
3384
0
              return FALSE;
3385
3386
0
    break;
3387
0
  case 'c':
3388
0
    {
3389
0
            const char *subformat = alt_era ? PREFERRED_ERA_DATE_TIME_FMT : PREFERRED_DATE_TIME_FMT;
3390
3391
            /* Fallback */
3392
0
            if (alt_era && g_strcmp0 (subformat, "") == 0)
3393
0
              subformat = PREFERRED_DATE_TIME_FMT;
3394
3395
0
            if (g_strcmp0 (subformat, "") == 0)
3396
0
              return FALSE;
3397
0
            if (!g_date_time_format_locale (datetime, subformat,
3398
0
                                            outstr, locale_is_utf8))
3399
0
              return FALSE;
3400
0
    }
3401
0
    break;
3402
0
  case 'C':
3403
0
          if (alt_era)
3404
0
            {
3405
0
              GEraDescriptionSegment *era = date_time_lookup_era (datetime, locale_is_utf8);
3406
0
              if (era != NULL)
3407
0
                {
3408
0
                  g_string_append (outstr, era->era_name);
3409
0
                  _g_era_description_segment_unref (era);
3410
0
                  break;
3411
0
                }
3412
0
            }
3413
3414
0
    format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
3415
0
       g_date_time_get_year (datetime) / 100);
3416
0
    break;
3417
0
  case 'd':
3418
0
    format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
3419
0
       g_date_time_get_day_of_month (datetime));
3420
0
    break;
3421
0
  case 'e':
3422
0
    format_number (outstr, alt_digits, pad_set ? pad : "\u2007", 2,
3423
0
       g_date_time_get_day_of_month (datetime));
3424
0
    break;
3425
0
  case 'f':
3426
0
    g_string_append_printf (outstr, "%06" G_GUINT64_FORMAT,
3427
0
      datetime->usec % G_TIME_SPAN_SECOND);
3428
0
    break;
3429
0
  case 'F':
3430
0
    g_string_append_printf (outstr, "%d-%02d-%02d",
3431
0
          g_date_time_get_year (datetime),
3432
0
          g_date_time_get_month (datetime),
3433
0
          g_date_time_get_day_of_month (datetime));
3434
0
    break;
3435
0
  case 'g':
3436
0
    format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
3437
0
       g_date_time_get_week_numbering_year (datetime) % 100);
3438
0
    break;
3439
0
  case 'G':
3440
0
    format_number (outstr, alt_digits, pad_set ? pad : 0, 0,
3441
0
       g_date_time_get_week_numbering_year (datetime));
3442
0
    break;
3443
0
  case 'h':
3444
0
    name = alt_digits ? MONTH_ABBR_STANDALONE (datetime)
3445
0
          : MONTH_ABBR_WITH_DAY (datetime);
3446
0
          if (g_strcmp0 (name, "") == 0)
3447
0
            return FALSE;
3448
3449
0
          name_is_utf8 = locale_is_utf8 ||
3450
0
            ((alt_digits && !MONTH_ABBR_STANDALONE_IS_LOCALE) ||
3451
0
             (!alt_digits && !MONTH_ABBR_WITH_DAY_IS_LOCALE));
3452
3453
0
          if (!string_append (outstr, name, mod_case, name_is_utf8))
3454
0
            return FALSE;
3455
3456
0
    break;
3457
0
  case 'H':
3458
0
    format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
3459
0
       g_date_time_get_hour (datetime));
3460
0
    break;
3461
0
  case 'I':
3462
0
    format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
3463
0
       (g_date_time_get_hour (datetime) + 11) % 12 + 1);
3464
0
    break;
3465
0
  case 'j':
3466
0
    format_number (outstr, alt_digits, pad_set ? pad : "0", 3,
3467
0
       g_date_time_get_day_of_year (datetime));
3468
0
    break;
3469
0
  case 'k':
3470
0
    format_number (outstr, alt_digits, pad_set ? pad : "\u2007", 2,
3471
0
       g_date_time_get_hour (datetime));
3472
0
    break;
3473
0
  case 'l':
3474
0
    format_number (outstr, alt_digits, pad_set ? pad : "\u2007", 2,
3475
0
       (g_date_time_get_hour (datetime) + 11) % 12 + 1);
3476
0
    break;
3477
0
  case 'm':
3478
0
    format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
3479
0
       g_date_time_get_month (datetime));
3480
0
    break;
3481
0
  case 'M':
3482
0
    format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
3483
0
       g_date_time_get_minute (datetime));
3484
0
    break;
3485
0
  case 'n':
3486
0
    g_string_append_c (outstr, '\n');
3487
0
    break;
3488
0
  case 'O':
3489
0
    alt_digits = TRUE;
3490
0
    goto next_mod;
3491
0
        case 'E':
3492
0
          alt_era = TRUE;
3493
0
          goto next_mod;
3494
0
  case 'p':
3495
0
          if (!format_ampm (datetime, outstr, locale_is_utf8,
3496
0
                            mod_case && g_strcmp0 (mod, "#") == 0 ? FALSE
3497
0
                                                                  : TRUE))
3498
0
            return FALSE;
3499
0
          break;
3500
0
  case 'P':
3501
0
          if (!format_ampm (datetime, outstr, locale_is_utf8,
3502
0
                            mod_case && g_strcmp0 (mod, "^") == 0 ? TRUE
3503
0
                                                                  : FALSE))
3504
0
            return FALSE;
3505
0
    break;
3506
0
  case 'r':
3507
0
    {
3508
0
            if (g_strcmp0 (PREFERRED_12HR_TIME_FMT, "") == 0)
3509
0
              return FALSE;
3510
0
      if (!g_date_time_format_locale (datetime, PREFERRED_12HR_TIME_FMT,
3511
0
              outstr, locale_is_utf8))
3512
0
        return FALSE;
3513
0
    }
3514
0
    break;
3515
0
  case 'R':
3516
0
    g_string_append_printf (outstr, "%02d:%02d",
3517
0
          g_date_time_get_hour (datetime),
3518
0
          g_date_time_get_minute (datetime));
3519
0
    break;
3520
0
  case 's':
3521
0
    g_string_append_printf (outstr, "%" G_GINT64_FORMAT, g_date_time_to_unix (datetime));
3522
0
    break;
3523
0
  case 'S':
3524
0
    format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
3525
0
       g_date_time_get_second (datetime));
3526
0
    break;
3527
0
  case 't':
3528
0
    g_string_append_c (outstr, '\t');
3529
0
    break;
3530
0
  case 'T':
3531
0
    g_string_append_printf (outstr, "%02d:%02d:%02d",
3532
0
          g_date_time_get_hour (datetime),
3533
0
          g_date_time_get_minute (datetime),
3534
0
          g_date_time_get_second (datetime));
3535
0
    break;
3536
0
  case 'u':
3537
0
    format_number (outstr, alt_digits, 0, 0,
3538
0
       g_date_time_get_day_of_week (datetime));
3539
0
    break;
3540
0
  case 'V':
3541
0
    format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
3542
0
       g_date_time_get_week_of_year (datetime));
3543
0
    break;
3544
0
  case 'w':
3545
0
    format_number (outstr, alt_digits, 0, 0,
3546
0
       g_date_time_get_day_of_week (datetime) % 7);
3547
0
    break;
3548
0
  case 'x':
3549
0
    {
3550
0
            const char *subformat = alt_era ? PREFERRED_ERA_DATE_FMT : PREFERRED_DATE_FMT;
3551
3552
            /* Fallback */
3553
0
            if (alt_era && g_strcmp0 (subformat, "") == 0)
3554
0
              subformat = PREFERRED_DATE_FMT;
3555
3556
0
            if (g_strcmp0 (subformat, "") == 0)
3557
0
              return FALSE;
3558
0
      if (!g_date_time_format_locale (datetime, subformat,
3559
0
              outstr, locale_is_utf8))
3560
0
        return FALSE;
3561
0
    }
3562
0
    break;
3563
0
  case 'X':
3564
0
    {
3565
0
            const char *subformat = alt_era ? PREFERRED_ERA_TIME_FMT : PREFERRED_TIME_FMT;
3566
3567
            /* Fallback */
3568
0
            if (alt_era && g_strcmp0 (subformat, "") == 0)
3569
0
              subformat = PREFERRED_TIME_FMT;
3570
3571
0
            if (g_strcmp0 (subformat, "") == 0)
3572
0
              return FALSE;
3573
0
      if (!g_date_time_format_locale (datetime, subformat,
3574
0
              outstr, locale_is_utf8))
3575
0
        return FALSE;
3576
0
    }
3577
0
    break;
3578
0
  case 'y':
3579
0
          if (alt_era)
3580
0
            {
3581
0
              GEraDescriptionSegment *era = date_time_lookup_era (datetime, locale_is_utf8);
3582
0
              if (era != NULL)
3583
0
                {
3584
0
                  int delta = g_date_time_get_year (datetime) - era->start_date.year;
3585
3586
                  /* Both these years are in the Gregorian calendar (CE/BCE),
3587
                   * which has no year zero. So take one from the delta if they
3588
                   * cross across where year zero would be. */
3589
0
                  if ((g_date_time_get_year (datetime) < 0) != (era->start_date.year < 0))
3590
0
                    delta -= 1;
3591
3592
0
                  format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
3593
0
                                 era->offset + delta * era->direction_multiplier);
3594
0
                  _g_era_description_segment_unref (era);
3595
0
                  break;
3596
0
                }
3597
0
            }
3598
3599
0
          format_number (outstr, alt_digits, pad_set ? pad : "0", 2,
3600
0
                         g_date_time_get_year (datetime) % 100);
3601
0
    break;
3602
0
  case 'Y':
3603
0
          if (alt_era)
3604
0
            {
3605
0
              GEraDescriptionSegment *era = date_time_lookup_era (datetime, locale_is_utf8);
3606
0
              if (era != NULL)
3607
0
                {
3608
0
                  if (!g_date_time_format_utf8 (datetime, era->era_format,
3609
0
                                                outstr, locale_is_utf8))
3610
0
                    {
3611
0
                      _g_era_description_segment_unref (era);
3612
0
                      return FALSE;
3613
0
                    }
3614
3615
0
                  _g_era_description_segment_unref (era);
3616
0
                  break;
3617
0
                }
3618
0
            }
3619
3620
0
          format_number (outstr, alt_digits, 0, 0,
3621
0
                         g_date_time_get_year (datetime));
3622
0
    break;
3623
0
  case 'z':
3624
0
    {
3625
0
      gint64 offset;
3626
0
      offset = g_date_time_get_utc_offset (datetime) / USEC_PER_SECOND;
3627
0
      if (!format_z (outstr, (int) offset, colons))
3628
0
        return FALSE;
3629
0
    }
3630
0
    break;
3631
0
  case 'Z':
3632
0
          tz = g_date_time_get_timezone_abbreviation (datetime);
3633
0
          if (mod_case && g_strcmp0 (mod, "#") == 0)
3634
0
            tz = tmp = g_utf8_strdown (tz, -1);
3635
0
          g_string_append (outstr, tz);
3636
0
          g_clear_pointer (&tmp, g_free);
3637
0
    break;
3638
0
  case '%':
3639
0
    g_string_append_c (outstr, '%');
3640
0
    break;
3641
0
  case '-':
3642
0
    pad_set = TRUE;
3643
0
    pad = "";
3644
0
    goto next_mod;
3645
0
  case '_':
3646
0
    pad_set = TRUE;
3647
0
    pad = " ";
3648
0
    goto next_mod;
3649
0
  case '0':
3650
0
    pad_set = TRUE;
3651
0
    pad = "0";
3652
0
    goto next_mod;
3653
0
  case ':':
3654
    /* Colons are only allowed before 'z' */
3655
0
    if (*utf8_format && *utf8_format != 'z' && *utf8_format != ':')
3656
0
      return FALSE;
3657
0
    colons++;
3658
0
    goto next_mod;
3659
0
        case '^':
3660
0
          mod_case = TRUE;
3661
0
          mod = "^";
3662
0
          goto next_mod;
3663
0
        case '#':
3664
0
          mod_case = TRUE;
3665
0
          mod = "#";
3666
0
          goto next_mod;
3667
0
        default:
3668
0
          return FALSE;
3669
0
        }
3670
0
    }
3671
3672
0
  return TRUE;
3673
0
}
3674
3675
/**
3676
 * g_date_time_format:
3677
 * @datetime: A #GDateTime
3678
 * @format: a valid UTF-8 string, containing the format for the
3679
 *          #GDateTime
3680
 *
3681
 * Creates a newly allocated string representing the requested @format.
3682
 *
3683
 * The format strings understood by this function are a subset of the
3684
 * `strftime()` format language as specified by C99.  The `%D`, `%U` and `%W`
3685
 * conversions are not supported, nor is the `E` modifier.  The GNU
3686
 * extensions `%k`, `%l`, `%s` and `%P` are supported, however, as are the
3687
 * `0`, `_` and `-` modifiers. The Python extension `%f` is also supported.
3688
 *
3689
 * In contrast to `strftime()`, this function always produces a UTF-8
3690
 * string, regardless of the current locale.  Note that the rendering of
3691
 * many formats is locale-dependent and may not match the `strftime()`
3692
 * output exactly.
3693
 *
3694
 * The following format specifiers are supported:
3695
 *
3696
 * - `%a`: the abbreviated weekday name according to the current locale
3697
 * - `%A`: the full weekday name according to the current locale
3698
 * - `%b`: the abbreviated month name according to the current locale
3699
 * - `%B`: the full month name according to the current locale
3700
 * - `%c`: the preferred date and time representation for the current locale
3701
 * - `%C`: the century number (year/100) as a 2-digit integer (00-99)
3702
 * - `%d`: the day of the month as a decimal number (range 01 to 31)
3703
 * - `%e`: the day of the month as a decimal number (range 1 to 31);
3704
 *   single digits are preceded by a figure space (U+2007)
3705
 * - `%F`: equivalent to `%Y-%m-%d` (the ISO 8601 date format)
3706
 * - `%g`: the last two digits of the ISO 8601 week-based year as a
3707
 *   decimal number (00-99). This works well with `%V` and `%u`.
3708
 * - `%G`: the ISO 8601 week-based year as a decimal number. This works
3709
 *   well with `%V` and `%u`.
3710
 * - `%h`: equivalent to `%b`
3711
 * - `%H`: the hour as a decimal number using a 24-hour clock (range 00 to 23)
3712
 * - `%I`: the hour as a decimal number using a 12-hour clock (range 01 to 12)
3713
 * - `%j`: the day of the year as a decimal number (range 001 to 366)
3714
 * - `%k`: the hour (24-hour clock) as a decimal number (range 0 to 23);
3715
 *   single digits are preceded by a figure space (U+2007)
3716
 * - `%l`: the hour (12-hour clock) as a decimal number (range 1 to 12);
3717
 *   single digits are preceded by a figure space (U+2007)
3718
 * - `%m`: the month as a decimal number (range 01 to 12)
3719
 * - `%M`: the minute as a decimal number (range 00 to 59)
3720
 * - `%f`: the microsecond as a decimal number (range 000000 to 999999)
3721
 * - `%p`: either ‘AM’ or ‘PM’ according to the given time value, or the
3722
 *   corresponding  strings for the current locale.  Noon is treated as
3723
 *   ‘PM’ and midnight as ‘AM’. Use of this format specifier is discouraged, as
3724
 *   many locales have no concept of AM/PM formatting. Use `%c` or `%X` instead.
3725
 * - `%P`: like `%p` but lowercase: ‘am’ or ‘pm’ or a corresponding string for
3726
 *   the current locale. Use of this format specifier is discouraged, as
3727
 *   many locales have no concept of AM/PM formatting. Use `%c` or `%X` instead.
3728
 * - `%r`: the time in a.m. or p.m. notation. Use of this format specifier is
3729
 *   discouraged, as many locales have no concept of AM/PM formatting. Use `%c`
3730
 *   or `%X` instead.
3731
 * - `%R`: the time in 24-hour notation (`%H:%M`)
3732
 * - `%s`: the number of seconds since the Epoch, that is, since 1970-01-01
3733
 *   00:00:00 UTC
3734
 * - `%S`: the second as a decimal number (range 00 to 60)
3735
 * - `%t`: a tab character
3736
 * - `%T`: the time in 24-hour notation with seconds (`%H:%M:%S`)
3737
 * - `%u`: the ISO 8601 standard day of the week as a decimal, range 1 to 7,
3738
 *    Monday being 1. This works well with `%G` and `%V`.
3739
 * - `%V`: the ISO 8601 standard week number of the current year as a decimal
3740
 *   number, range 01 to 53, where week 1 is the first week that has at
3741
 *   least 4 days in the new year. See g_date_time_get_week_of_year().
3742
 *   This works well with `%G` and `%u`.
3743
 * - `%w`: the day of the week as a decimal, range 0 to 6, Sunday being 0.
3744
 *   This is not the ISO 8601 standard format — use `%u` instead.
3745
 * - `%x`: the preferred date representation for the current locale without
3746
 *   the time
3747
 * - `%X`: the preferred time representation for the current locale without
3748
 *   the date
3749
 * - `%y`: the year as a decimal number without the century
3750
 * - `%Y`: the year as a decimal number including the century
3751
 * - `%z`: the time zone as an offset from UTC (`+hhmm`)
3752
 * - `%:z`: the time zone as an offset from UTC (`+hh:mm`).
3753
 *   This is a gnulib `strftime()` extension. Since: 2.38
3754
 * - `%::z`: the time zone as an offset from UTC (`+hh:mm:ss`). This is a
3755
 *   gnulib `strftime()` extension. Since: 2.38
3756
 * - `%:::z`: the time zone as an offset from UTC, with `:` to necessary
3757
 *   precision (e.g., `-04`, `+05:30`). This is a gnulib `strftime()` extension. Since: 2.38
3758
 * - `%Z`: the time zone or name or abbreviation
3759
 * - `%%`: a literal `%` character
3760
 *
3761
 * Some conversion specifications can be modified by preceding the
3762
 * conversion specifier by one or more modifier characters.
3763
 *
3764
 * The following modifiers are supported for many of the numeric
3765
 * conversions:
3766
 *
3767
 * - `O`: Use alternative numeric symbols, if the current locale supports those.
3768
 * - `_`: Pad a numeric result with spaces. This overrides the default padding
3769
 *   for the specifier.
3770
 * - `-`: Do not pad a numeric result. This overrides the default padding
3771
 *   for the specifier.
3772
 * - `0`: Pad a numeric result with zeros. This overrides the default padding
3773
 *   for the specifier.
3774
 *
3775
 * The following modifiers are supported for many of the alphabetic conversions:
3776
 *
3777
 * - `^`: Use upper case if possible. This is a gnulib `strftime()` extension.
3778
 *   Since: 2.80
3779
 * - `#`: Use opposite case if possible. This is a gnulib `strftime()`
3780
 *   extension. Since: 2.80
3781
 *
3782
 * Additionally, when `O` is used with `B`, `b`, or `h`, it produces the alternative
3783
 * form of a month name. The alternative form should be used when the month
3784
 * name is used without a day number (e.g., standalone). It is required in
3785
 * some languages (Baltic, Slavic, Greek, and more) due to their grammatical
3786
 * rules. For other languages there is no difference. `%OB` is a GNU and BSD
3787
 * `strftime()` extension expected to be added to the future POSIX specification,
3788
 * `%Ob` and `%Oh` are GNU `strftime()` extensions. Since: 2.56
3789
 *
3790
 * Since GLib 2.80, when `E` is used with `%c`, `%C`, `%x`, `%X`, `%y` or `%Y`,
3791
 * the date is formatted using an alternate era representation specific to the
3792
 * locale. This is typically used for the Thai solar calendar or Japanese era
3793
 * names, for example.
3794
 *
3795
 * - `%Ec`: the preferred date and time representation for the current locale,
3796
 *   using the alternate era representation
3797
 * - `%EC`: the name of the era
3798
 * - `%Ex`: the preferred date representation for the current locale without
3799
 *   the time, using the alternate era representation
3800
 * - `%EX`: the preferred time representation for the current locale without
3801
 *   the date, using the alternate era representation
3802
 * - `%Ey`: the year since the beginning of the era denoted by the `%EC`
3803
 *   specifier
3804
 * - `%EY`: the full alternative year representation
3805
 *
3806
 * Returns: (transfer full) (nullable): a newly allocated string formatted to
3807
 *    the requested format or %NULL in the case that there was an error (such
3808
 *    as a format specifier not being supported in the current locale). The
3809
 *    string should be freed with g_free().
3810
 *
3811
 * Since: 2.26
3812
 */
3813
gchar *
3814
g_date_time_format (GDateTime   *datetime,
3815
                    const gchar *format)
3816
0
{
3817
0
  GString  *outstr;
3818
0
  const gchar *charset;
3819
  /* Avoid conversions from locale (for LC_TIME and not for LC_MESSAGES unless
3820
   * specified otherwise) charset to UTF-8 if charset is compatible
3821
   * with UTF-8 already. Check for UTF-8 and synonymous canonical names of
3822
   * ASCII. */
3823
0
  gboolean time_is_utf8_compatible = _g_get_time_charset (&charset) ||
3824
0
    g_strcmp0 ("ASCII", charset) == 0 ||
3825
0
    g_strcmp0 ("ANSI_X3.4-1968", charset) == 0;
3826
3827
0
  g_return_val_if_fail (datetime != NULL, NULL);
3828
0
  g_return_val_if_fail (format != NULL, NULL);
3829
0
  g_return_val_if_fail (g_utf8_validate (format, -1, NULL), NULL);
3830
3831
0
  outstr = g_string_sized_new (strlen (format) * 2);
3832
3833
0
  if (!g_date_time_format_utf8 (datetime, format, outstr,
3834
0
                                time_is_utf8_compatible))
3835
0
    {
3836
0
      g_string_free (outstr, TRUE);
3837
0
      return NULL;
3838
0
    }
3839
3840
0
  return g_string_free (outstr, FALSE);
3841
0
}
3842
3843
/**
3844
 * g_date_time_format_iso8601:
3845
 * @datetime: A #GDateTime
3846
 *
3847
 * Format @datetime in [ISO 8601 format](https://en.wikipedia.org/wiki/ISO_8601),
3848
 * including the date, time and time zone, and return that as a UTF-8 encoded
3849
 * string.
3850
 *
3851
 * Since GLib 2.66, this will output to sub-second precision if needed.
3852
 *
3853
 * Returns: (transfer full) (nullable): a newly allocated string formatted in
3854
 *   ISO 8601 format or %NULL in the case that there was an error. The string
3855
 *   should be freed with g_free().
3856
 *
3857
 * Since: 2.62
3858
 */
3859
gchar *
3860
g_date_time_format_iso8601 (GDateTime *datetime)
3861
0
{
3862
0
  GString *outstr = NULL;
3863
0
  gchar *main_date = NULL;
3864
0
  gint64 offset;
3865
0
  gchar *format = "%C%y-%m-%dT%H:%M:%S";
3866
3867
0
  g_return_val_if_fail (datetime != NULL, NULL);
3868
3869
  /* if datetime has sub-second non-zero values below the second precision we
3870
   * should print them as well */
3871
0
  if (datetime->usec % G_TIME_SPAN_SECOND != 0)
3872
0
    format = "%C%y-%m-%dT%H:%M:%S.%f";
3873
3874
  /* Main date and time. */
3875
0
  main_date = g_date_time_format (datetime, format);
3876
0
  outstr = g_string_new (main_date);
3877
0
  g_free (main_date);
3878
3879
  /* Timezone. Format it as `%:::z` unless the offset is zero, in which case
3880
   * we can simply use `Z`. */
3881
0
  offset = g_date_time_get_utc_offset (datetime);
3882
3883
0
  if (offset == 0)
3884
0
    {
3885
0
      g_string_append_c (outstr, 'Z');
3886
0
    }
3887
0
  else
3888
0
    {
3889
0
      gchar *time_zone = g_date_time_format (datetime, "%:::z");
3890
0
      g_string_append (outstr, time_zone);
3891
0
      g_free (time_zone);
3892
0
    }
3893
3894
0
  return g_string_free (outstr, FALSE);
3895
0
}
3896
3897
3898
/* Epilogue {{{1 */
3899
/* vim:set foldmethod=marker: */