Coverage Report

Created: 2026-05-16 06:18

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