Coverage Report

Created: 2025-09-05 06:29

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