Coverage Report

Created: 2025-12-31 06:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/glib/glib/gdate.c
Line
Count
Source
1
/* GLIB - Library of useful routines for C programming
2
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3
 *
4
 * SPDX-License-Identifier: LGPL-2.1-or-later
5
 *
6
 * This library is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * This library is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
/*
21
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22
 * file for a list of people on the GLib Team.  See the ChangeLog
23
 * files for a list of changes.  These files are distributed with
24
 * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25
 */
26
27
/* 
28
 * MT safe
29
 */
30
31
#include "config.h"
32
#include "glibconfig.h"
33
34
#define DEBUG_MSG(x)  /* */
35
#ifdef G_ENABLE_DEBUG
36
/* #define DEBUG_MSG(args)  g_message args ; */
37
#endif
38
39
#include <time.h>
40
#include <string.h>
41
#include <stdlib.h>
42
#include <locale.h>
43
44
#ifdef G_OS_WIN32
45
#include <windows.h>
46
#endif
47
48
#include "gdate.h"
49
50
#include "gconvert.h"
51
#include "gmem.h"
52
#include "gstrfuncs.h"
53
#include "gtestutils.h"
54
#include "gthread.h"
55
#include "gunicode.h"
56
#include "gutilsprivate.h"
57
58
#ifdef G_OS_WIN32
59
#include "garray.h"
60
#endif
61
62
/**
63
 * GDate:
64
 * @julian_days: the Julian representation of the date
65
 * @julian: this bit is set if @julian_days is valid
66
 * @dmy: this is set if @day, @month and @year are valid
67
 * @day: the day of the day-month-year representation of the date,
68
 *   as a number between 1 and 31
69
 * @month: the month of the day-month-year representation of the date,
70
 *   as a number between 1 and 12
71
 * @year: the year of the day-month-year representation of the date
72
 *
73
 * `GDate` is a struct for calendrical calculations.
74
 *
75
 * The `GDate` data structure represents a day between January 1, Year 1,
76
 * and sometime a few thousand years in the future (right now it will go
77
 * to the year 65535 or so, but [method@GLib.Date.set_parse] only parses up to the
78
 * year 8000 or so - just count on "a few thousand"). `GDate` is meant to
79
 * represent everyday dates, not astronomical dates or historical dates
80
 * or ISO timestamps or the like. It extrapolates the current Gregorian
81
 * calendar forward and backward in time; there is no attempt to change
82
 * the calendar to match time periods or locations. `GDate` does not store
83
 * time information; it represents a day.
84
 *
85
 * The `GDate` implementation has several nice features; it is only a
86
 * 64-bit struct, so storing large numbers of dates is very efficient. It
87
 * can keep both a Julian and day-month-year representation of the date,
88
 * since some calculations are much easier with one representation or the
89
 * other. A Julian representation is simply a count of days since some
90
 * fixed day in the past; for #GDate the fixed day is January 1, 1 AD.
91
 * ("Julian" dates in the #GDate API aren't really Julian dates in the
92
 * technical sense; technically, Julian dates count from the start of the
93
 * Julian period, Jan 1, 4713 BC).
94
 *
95
 * `GDate` is simple to use. First you need a "blank" date; you can get a
96
 * dynamically allocated date from [ctor@GLib.Date.new], or you can declare an
97
 * automatic variable or array and initialize it by calling [method@GLib.Date.clear].
98
 * A cleared date is safe; it's safe to call [method@GLib.Date.set_dmy] and the other
99
 * mutator functions to initialize the value of a cleared date. However, a cleared date
100
 * is initially invalid, meaning that it doesn't represent a day that exists.
101
 * It is undefined to call any of the date calculation routines on an invalid date.
102
 * If you obtain a date from a user or other unpredictable source, you should check
103
 * its validity with the [method@GLib.Date.valid] predicate. [method@GLib.Date.valid]
104
 * is also used to check for errors with [method@GLib.Date.set_parse] and other functions
105
 * that can fail. Dates can be invalidated by calling [method@GLib.Date.clear] again.
106
 *
107
 * It is very important to use the API to access the `GDate` struct. Often only the
108
 * day-month-year or only the Julian representation is valid. Sometimes neither is valid.
109
 * Use the API.
110
 *
111
 * GLib also features `GDateTime` which represents a precise time.
112
 */
113
114
/**
115
 * G_USEC_PER_SEC:
116
 *
117
 * Number of microseconds in one second (1 million).
118
 * This macro is provided for code readability.
119
 */
120
121
/**
122
 * GTimeVal:
123
 * @tv_sec: seconds
124
 * @tv_usec: microseconds
125
 *
126
 * Represents a precise time, with seconds and microseconds.
127
 *
128
 * Similar to the struct timeval returned by the `gettimeofday()`
129
 * UNIX system call.
130
 *
131
 * GLib is attempting to unify around the use of 64-bit integers to
132
 * represent microsecond-precision time. As such, this type will be
133
 * removed from a future version of GLib. A consequence of using `glong` for
134
 * `tv_sec` is that on 32-bit systems `GTimeVal` is subject to the year 2038
135
 * problem.
136
 *
137
 * Deprecated: 2.62: Use #GDateTime or #guint64 instead.
138
 */
139
140
/**
141
 * GTime:
142
 *
143
 * Simply a replacement for `time_t`. It has been deprecated
144
 * since it is not equivalent to `time_t` on 64-bit platforms
145
 * with a 64-bit `time_t`.
146
 *
147
 * Unrelated to #GTimer.
148
 *
149
 * Note that #GTime is defined to always be a 32-bit integer,
150
 * unlike `time_t` which may be 64-bit on some systems. Therefore,
151
 * #GTime will overflow in the year 2038, and you cannot use the
152
 * address of a #GTime variable as argument to the UNIX time()
153
 * function.
154
 *
155
 * Instead, do the following:
156
 *
157
 * |[<!-- language="C" -->
158
 * time_t ttime;
159
 * GTime gtime;
160
 *
161
 * time (&ttime);
162
 * gtime = (GTime)ttime;
163
 * ]|
164
 *
165
 * Deprecated: 2.62: This is not [Y2038-safe](https://en.wikipedia.org/wiki/Year_2038_problem).
166
 *    Use #GDateTime or #time_t instead.
167
 */
168
169
/**
170
 * GDateDMY:
171
 * @G_DATE_DAY: a day
172
 * @G_DATE_MONTH: a month
173
 * @G_DATE_YEAR: a year
174
 *
175
 * This enumeration isn't used in the API, but may be useful if you need
176
 * to mark a number as a day, month, or year.
177
 */
178
179
/**
180
 * GDateDay:
181
 *
182
 * Integer representing a day of the month; between 1 and 31.
183
 *
184
 * The %G_DATE_BAD_DAY value represents an invalid day of the month.
185
 */
186
187
/**
188
 * GDateMonth:
189
 * @G_DATE_BAD_MONTH: invalid value
190
 * @G_DATE_JANUARY: January
191
 * @G_DATE_FEBRUARY: February
192
 * @G_DATE_MARCH: March
193
 * @G_DATE_APRIL: April
194
 * @G_DATE_MAY: May
195
 * @G_DATE_JUNE: June
196
 * @G_DATE_JULY: July
197
 * @G_DATE_AUGUST: August
198
 * @G_DATE_SEPTEMBER: September
199
 * @G_DATE_OCTOBER: October
200
 * @G_DATE_NOVEMBER: November
201
 * @G_DATE_DECEMBER: December
202
 *
203
 * Enumeration representing a month; values are %G_DATE_JANUARY,
204
 * %G_DATE_FEBRUARY, etc. %G_DATE_BAD_MONTH is the invalid value.
205
 */
206
207
/**
208
 * GDateYear:
209
 *
210
 * Integer type representing a year.
211
 *
212
 * The %G_DATE_BAD_YEAR value is the invalid value. The year
213
 * must be 1 or higher; negative ([BCE](https://en.wikipedia.org/wiki/Common_Era))
214
 * years are not allowed.
215
 *
216
 * The year is represented with four digits.
217
 */
218
219
/**
220
 * GDateWeekday:
221
 * @G_DATE_BAD_WEEKDAY: invalid value
222
 * @G_DATE_MONDAY: Monday
223
 * @G_DATE_TUESDAY: Tuesday
224
 * @G_DATE_WEDNESDAY: Wednesday
225
 * @G_DATE_THURSDAY: Thursday
226
 * @G_DATE_FRIDAY: Friday
227
 * @G_DATE_SATURDAY: Saturday
228
 * @G_DATE_SUNDAY: Sunday
229
 *
230
 * Enumeration representing a day of the week; %G_DATE_MONDAY,
231
 * %G_DATE_TUESDAY, etc. %G_DATE_BAD_WEEKDAY is an invalid weekday.
232
 */
233
234
/**
235
 * G_DATE_BAD_DAY:
236
 *
237
 * Represents an invalid #GDateDay.
238
 */
239
240
/**
241
 * G_DATE_BAD_JULIAN:
242
 *
243
 * Represents an invalid Julian day number.
244
 */
245
246
/**
247
 * G_DATE_BAD_YEAR:
248
 *
249
 * Represents an invalid year.
250
 */
251
252
/**
253
 * g_date_new:
254
 *
255
 * Allocates a #GDate and initializes
256
 * it to a safe state. The new date will
257
 * be cleared (as if you'd called g_date_clear()) but invalid (it won't
258
 * represent an existing day). Free the return value with g_date_free().
259
 *
260
 * Returns: a newly-allocated #GDate
261
 */
262
GDate*
263
g_date_new (void)
264
0
{
265
0
  GDate *d = g_new0 (GDate, 1); /* happily, 0 is the invalid flag for everything. */
266
  
267
0
  return d;
268
0
}
269
270
/**
271
 * g_date_new_dmy:
272
 * @day: day of the month
273
 * @month: month of the year
274
 * @year: year
275
 *
276
 * Create a new #GDate representing the given day-month-year triplet.
277
 *
278
 * The triplet you pass in must represent a valid date. Use g_date_valid_dmy()
279
 * if needed to validate it. The returned #GDate is guaranteed to be non-%NULL
280
 * and valid.
281
 *
282
 * Returns: (transfer full) (not nullable): a newly-allocated #GDate
283
 *   initialized with @day, @month, and @year
284
 */
285
GDate*
286
g_date_new_dmy (GDateDay   day, 
287
                GDateMonth m, 
288
                GDateYear  y)
289
0
{
290
0
  GDate *d;
291
0
  g_return_val_if_fail (g_date_valid_dmy (day, m, y), NULL);
292
  
293
0
  d = g_new (GDate, 1);
294
  
295
0
  d->julian = FALSE;
296
0
  d->dmy    = TRUE;
297
  
298
0
  d->month = m;
299
0
  d->day   = day;
300
0
  d->year  = y;
301
  
302
0
  g_assert (g_date_valid (d));
303
  
304
0
  return d;
305
0
}
306
307
/**
308
 * g_date_new_julian:
309
 * @julian_day: days since January 1, Year 1
310
 *
311
 * Create a new #GDate representing the given Julian date.
312
 *
313
 * The @julian_day you pass in must be valid. Use g_date_valid_julian() if
314
 * needed to validate it. The returned #GDate is guaranteed to be non-%NULL and
315
 * valid.
316
 *
317
 * Returns: (transfer full) (not nullable): a newly-allocated #GDate initialized
318
 *   with @julian_day
319
 */
320
GDate*
321
g_date_new_julian (guint32 julian_day)
322
0
{
323
0
  GDate *d;
324
0
  g_return_val_if_fail (g_date_valid_julian (julian_day), NULL);
325
  
326
0
  d = g_new (GDate, 1);
327
  
328
0
  d->julian = TRUE;
329
0
  d->dmy    = FALSE;
330
  
331
0
  d->julian_days = julian_day;
332
  
333
0
  g_assert (g_date_valid (d));
334
  
335
0
  return d;
336
0
}
337
338
/**
339
 * g_date_free:
340
 * @date: a #GDate to free
341
 *
342
 * Frees a #GDate returned from g_date_new().
343
 */
344
void
345
g_date_free (GDate *date)
346
0
{
347
0
  g_return_if_fail (date != NULL);
348
  
349
0
  g_free (date);
350
0
}
351
352
/**
353
 * g_date_copy:
354
 * @date: a #GDate to copy
355
 *
356
 * Copies a GDate to a newly-allocated GDate. If the input was invalid
357
 * (as determined by g_date_valid()), the invalid state will be copied
358
 * as is into the new object.
359
 *
360
 * Returns: (transfer full): a newly-allocated #GDate initialized from @date
361
 *
362
 * Since: 2.56
363
 */
364
GDate *
365
g_date_copy (const GDate *date)
366
0
{
367
0
  GDate *res;
368
0
  g_return_val_if_fail (date != NULL, NULL);
369
370
0
  if (g_date_valid (date))
371
0
    res = g_date_new_julian (g_date_get_julian (date));
372
0
  else
373
0
    {
374
0
      res = g_date_new ();
375
0
      *res = *date;
376
0
    }
377
378
0
  return res;
379
0
}
380
381
/**
382
 * g_date_valid:
383
 * @date: a #GDate to check
384
 *
385
 * Returns %TRUE if the #GDate represents an existing day. The date must not
386
 * contain garbage; it should have been initialized with g_date_clear()
387
 * if it wasn't allocated by one of the g_date_new() variants.
388
 *
389
 * Returns: Whether the date is valid
390
 */
391
gboolean     
392
g_date_valid (const GDate *d)
393
0
{
394
0
  g_return_val_if_fail (d != NULL, FALSE);
395
  
396
0
  return (d->julian || d->dmy);
397
0
}
398
399
static const guint8 days_in_months[2][13] = 
400
{  /* error, jan feb mar apr may jun jul aug sep oct nov dec */
401
  {  0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, 
402
  {  0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } /* leap year */
403
};
404
405
static const guint16 days_in_year[2][14] = 
406
{  /* 0, jan feb mar apr may  jun  jul  aug  sep  oct  nov  dec */
407
  {  0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, 
408
  {  0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
409
};
410
411
/**
412
 * g_date_valid_month:
413
 * @month: month
414
 *
415
 * Returns %TRUE if the month value is valid. The 12 #GDateMonth
416
 * enumeration values are the only valid months.
417
 *
418
 * Returns: %TRUE if the month is valid
419
 */
420
gboolean     
421
g_date_valid_month (GDateMonth m)
422
0
{ 
423
0
  return (((gint) m > G_DATE_BAD_MONTH) && ((gint) m < 13));
424
0
}
425
426
/**
427
 * g_date_valid_year:
428
 * @year: year
429
 *
430
 * Returns %TRUE if the year is valid. Any year greater than 0 is valid,
431
 * though there is a 16-bit limit to what #GDate will understand.
432
 *
433
 * Returns: %TRUE if the year is valid
434
 */
435
gboolean     
436
g_date_valid_year (GDateYear y)
437
0
{
438
0
  return ( y > G_DATE_BAD_YEAR );
439
0
}
440
441
/**
442
 * g_date_valid_day:
443
 * @day: day to check
444
 *
445
 * Returns %TRUE if the day of the month is valid (a day is valid if it's
446
 * between 1 and 31 inclusive).
447
 *
448
 * Returns: %TRUE if the day is valid
449
 */
450
451
gboolean     
452
g_date_valid_day (GDateDay d)
453
0
{
454
0
  return ( (d > G_DATE_BAD_DAY) && (d < 32) );
455
0
}
456
457
/**
458
 * g_date_valid_weekday:
459
 * @weekday: weekday
460
 *
461
 * Returns %TRUE if the weekday is valid. The seven #GDateWeekday enumeration
462
 * values are the only valid weekdays.
463
 *
464
 * Returns: %TRUE if the weekday is valid
465
 */
466
gboolean     
467
g_date_valid_weekday (GDateWeekday w)
468
0
{
469
0
  return (((gint) w > G_DATE_BAD_WEEKDAY) && ((gint) w < 8));
470
0
}
471
472
/**
473
 * g_date_valid_julian:
474
 * @julian_date: Julian day to check
475
 *
476
 * Returns %TRUE if the Julian day is valid. Anything greater than zero
477
 * is basically a valid Julian, though there is a 32-bit limit.
478
 *
479
 * Returns: %TRUE if the Julian day is valid
480
 */
481
gboolean     
482
g_date_valid_julian (guint32 j)
483
0
{
484
0
  return (j > G_DATE_BAD_JULIAN);
485
0
}
486
487
/**
488
 * g_date_valid_dmy:
489
 * @day: day
490
 * @month: month
491
 * @year: year
492
 *
493
 * Returns %TRUE if the day-month-year triplet forms a valid, existing day
494
 * in the range of days #GDate understands (Year 1 or later, no more than
495
 * a few thousand years in the future).
496
 *
497
 * Returns: %TRUE if the date is a valid one
498
 */
499
gboolean     
500
g_date_valid_dmy (GDateDay   d, 
501
                  GDateMonth m, 
502
      GDateYear  y)
503
0
{
504
  /* No need to check the upper bound of @y, because #GDateYear is 16 bits wide,
505
   * just like #GDate.year. */
506
0
  return ( (m > G_DATE_BAD_MONTH) &&
507
0
           (m < 13)               && 
508
0
           (d > G_DATE_BAD_DAY)   && 
509
0
           (y > G_DATE_BAD_YEAR)  &&   /* must check before using g_date_is_leap_year */
510
0
           (d <=  (g_date_is_leap_year (y) ? 
511
0
       days_in_months[1][m] : days_in_months[0][m])) );
512
0
}
513
514
515
/* "Julian days" just means an absolute number of days, where Day 1 ==
516
 *   Jan 1, Year 1
517
 */
518
static void
519
g_date_update_julian (const GDate *const_d)
520
0
{
521
0
  GDate *d = (GDate *) const_d;
522
0
  GDateYear year;
523
0
  gint idx;
524
  
525
0
  g_return_if_fail (d != NULL);
526
0
  g_return_if_fail (d->dmy != 0);
527
0
  g_return_if_fail (!d->julian);
528
0
  g_return_if_fail (g_date_valid_dmy (d->day, d->month, d->year));
529
  
530
  /* What we actually do is: multiply years * 365 days in the year,
531
   * add the number of years divided by 4, subtract the number of
532
   * years divided by 100 and add the number of years divided by 400,
533
   * which accounts for leap year stuff. Code from Steffen Beyer's
534
   * DateCalc. 
535
   */
536
  
537
0
  year = d->year - 1; /* we know d->year > 0 since it's valid */
538
  
539
0
  d->julian_days = year * 365U;
540
0
  d->julian_days += (year >>= 2); /* divide by 4 and add */
541
0
  d->julian_days -= (year /= 25); /* divides original # years by 100 */
542
0
  d->julian_days += year >> 2;    /* divides by 4, which divides original by 400 */
543
  
544
0
  idx = g_date_is_leap_year (d->year) ? 1 : 0;
545
  
546
0
  d->julian_days += days_in_year[idx][d->month] + d->day;
547
  
548
0
  g_return_if_fail (g_date_valid_julian (d->julian_days));
549
  
550
0
  d->julian = TRUE;
551
0
}
552
553
static void 
554
g_date_update_dmy (const GDate *const_d)
555
0
{
556
0
  GDate *d = (GDate *) const_d;
557
0
  GDateYear y;
558
0
  GDateMonth m;
559
0
  GDateDay day;
560
  
561
0
  guint32 A, B, C, D, E, M;
562
  
563
0
  g_return_if_fail (d != NULL);
564
0
  g_return_if_fail (d->julian);
565
0
  g_return_if_fail (!d->dmy);
566
0
  g_return_if_fail (g_date_valid_julian (d->julian_days));
567
  
568
  /* Formula taken from the Calendar FAQ; the formula was for the
569
   *  Julian Period which starts on 1 January 4713 BC, so we add
570
   *  1,721,425 to the number of days before doing the formula.
571
   *
572
   * I'm sure this can be simplified for our 1 January 1 AD period
573
   * start, but I can't figure out how to unpack the formula.  
574
   */
575
  
576
0
  A = d->julian_days + 1721425 + 32045;
577
0
  B = ( 4 *(A + 36524) )/ 146097 - 1;
578
0
  C = A - (146097 * B)/4;
579
0
  D = ( 4 * (C + 365) ) / 1461 - 1;
580
0
  E = C - ((1461*D) / 4);
581
0
  M = (5 * (E - 1) + 2)/153;
582
  
583
0
  m = M + 3 - (12*(M/10));
584
0
  day = E - (153*M + 2)/5;
585
0
  y = 100 * B + D - 4800 + (M/10);
586
  
587
0
#ifdef G_ENABLE_DEBUG
588
0
  if (!g_date_valid_dmy (day, m, y)) 
589
0
    g_warning ("OOPS julian: %u  computed dmy: %u %u %u",
590
0
         d->julian_days, day, m, y);
591
0
#endif
592
  
593
0
  d->month = m;
594
0
  d->day   = day;
595
0
  d->year  = y;
596
  
597
0
  d->dmy = TRUE;
598
0
}
599
600
/**
601
 * g_date_get_weekday:
602
 * @date: a #GDate
603
 *
604
 * Returns the day of the week for a #GDate. The date must be valid.
605
 *
606
 * Returns: day of the week as a #GDateWeekday.
607
 */
608
GDateWeekday 
609
g_date_get_weekday (const GDate *d)
610
0
{
611
0
  g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_WEEKDAY);
612
  
613
0
  if (!d->julian) 
614
0
    g_date_update_julian (d);
615
616
0
  g_return_val_if_fail (d->julian, G_DATE_BAD_WEEKDAY);
617
  
618
0
  return ((d->julian_days - 1) % 7) + 1;
619
0
}
620
621
/**
622
 * g_date_get_month:
623
 * @date: a #GDate to get the month from
624
 *
625
 * Returns the month of the year. The date must be valid.
626
 *
627
 * Returns: month of the year as a #GDateMonth
628
 */
629
GDateMonth   
630
g_date_get_month (const GDate *d)
631
0
{
632
0
  g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_MONTH);
633
  
634
0
  if (!d->dmy) 
635
0
    g_date_update_dmy (d);
636
637
0
  g_return_val_if_fail (d->dmy, G_DATE_BAD_MONTH);
638
  
639
0
  return d->month;
640
0
}
641
642
/**
643
 * g_date_get_year:
644
 * @date: a #GDate
645
 *
646
 * Returns the year of a #GDate. The date must be valid.
647
 *
648
 * Returns: year in which the date falls
649
 */
650
GDateYear    
651
g_date_get_year (const GDate *d)
652
0
{
653
0
  g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_YEAR);
654
  
655
0
  if (!d->dmy) 
656
0
    g_date_update_dmy (d);
657
658
0
  g_return_val_if_fail (d->dmy, G_DATE_BAD_YEAR);  
659
  
660
0
  return d->year;
661
0
}
662
663
/**
664
 * g_date_get_day:
665
 * @date: a #GDate to extract the day of the month from
666
 *
667
 * Returns the day of the month. The date must be valid.
668
 *
669
 * Returns: day of the month
670
 */
671
GDateDay     
672
g_date_get_day (const GDate *d)
673
0
{
674
0
  g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_DAY);
675
  
676
0
  if (!d->dmy) 
677
0
    g_date_update_dmy (d);
678
679
0
  g_return_val_if_fail (d->dmy, G_DATE_BAD_DAY);  
680
  
681
0
  return d->day;
682
0
}
683
684
/**
685
 * g_date_get_julian:
686
 * @date: a #GDate to extract the Julian day from
687
 *
688
 * Returns the Julian day or "serial number" of the #GDate. The
689
 * Julian day is simply the number of days since January 1, Year 1; i.e.,
690
 * January 1, Year 1 is Julian day 1; January 2, Year 1 is Julian day 2,
691
 * etc. The date must be valid.
692
 *
693
 * Returns: Julian day
694
 */
695
guint32      
696
g_date_get_julian (const GDate *d)
697
0
{
698
0
  g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_JULIAN);
699
  
700
0
  if (!d->julian) 
701
0
    g_date_update_julian (d);
702
703
0
  g_return_val_if_fail (d->julian, G_DATE_BAD_JULIAN);  
704
  
705
0
  return d->julian_days;
706
0
}
707
708
/**
709
 * g_date_get_day_of_year:
710
 * @date: a #GDate to extract day of year from
711
 *
712
 * Returns the day of the year, where Jan 1 is the first day of the
713
 * year. The date must be valid.
714
 *
715
 * Returns: day of the year
716
 */
717
guint        
718
g_date_get_day_of_year (const GDate *d)
719
0
{
720
0
  gint idx;
721
  
722
0
  g_return_val_if_fail (g_date_valid (d), 0);
723
  
724
0
  if (!d->dmy) 
725
0
    g_date_update_dmy (d);
726
727
0
  g_return_val_if_fail (d->dmy, 0);  
728
  
729
0
  idx = g_date_is_leap_year (d->year) ? 1 : 0;
730
  
731
0
  return (days_in_year[idx][d->month] + d->day);
732
0
}
733
734
/**
735
 * g_date_get_monday_week_of_year:
736
 * @date: a #GDate
737
 *
738
 * Returns the week of the year, where weeks are understood to start on
739
 * Monday. If the date is before the first Monday of the year, return 0.
740
 * The date must be valid.
741
 *
742
 * Returns: week of the year
743
 */
744
guint        
745
g_date_get_monday_week_of_year (const GDate *d)
746
0
{
747
0
  GDateWeekday wd;
748
0
  guint day;
749
0
  GDate first;
750
  
751
0
  g_return_val_if_fail (g_date_valid (d), 0);
752
  
753
0
  if (!d->dmy) 
754
0
    g_date_update_dmy (d);
755
756
0
  g_return_val_if_fail (d->dmy, 0);  
757
  
758
0
  g_date_clear (&first, 1);
759
  
760
0
  g_date_set_dmy (&first, 1, 1, d->year);
761
  
762
0
  wd = g_date_get_weekday (&first) - 1; /* make Monday day 0 */
763
0
  day = g_date_get_day_of_year (d) - 1;
764
  
765
0
  return ((day + wd)/7U + (wd == 0 ? 1 : 0));
766
0
}
767
768
/**
769
 * g_date_get_sunday_week_of_year:
770
 * @date: a #GDate
771
 *
772
 * Returns the week of the year during which this date falls, if
773
 * weeks are understood to begin on Sunday. The date must be valid.
774
 * Can return 0 if the day is before the first Sunday of the year.
775
 *
776
 * Returns: week number
777
 */
778
guint        
779
g_date_get_sunday_week_of_year (const GDate *d)
780
0
{
781
0
  GDateWeekday wd;
782
0
  guint day;
783
0
  GDate first;
784
  
785
0
  g_return_val_if_fail (g_date_valid (d), 0);
786
  
787
0
  if (!d->dmy) 
788
0
    g_date_update_dmy (d);
789
790
0
  g_return_val_if_fail (d->dmy, 0);  
791
  
792
0
  g_date_clear (&first, 1);
793
  
794
0
  g_date_set_dmy (&first, 1, 1, d->year);
795
  
796
0
  wd = g_date_get_weekday (&first);
797
0
  if (wd == 7) wd = 0; /* make Sunday day 0 */
798
0
  day = g_date_get_day_of_year (d) - 1;
799
  
800
0
  return ((day + wd)/7U + (wd == 0 ? 1 : 0));
801
0
}
802
803
/**
804
 * g_date_get_iso8601_week_of_year:
805
 * @date: a valid #GDate
806
 *
807
 * Returns the week of the year, where weeks are interpreted according
808
 * to ISO 8601. 
809
 * 
810
 * Returns: ISO 8601 week number of the year.
811
 *
812
 * Since: 2.6
813
 **/
814
guint
815
g_date_get_iso8601_week_of_year (const GDate *d)
816
0
{
817
0
  guint j, d4, L, d1, w;
818
819
0
  g_return_val_if_fail (g_date_valid (d), 0);
820
  
821
0
  if (!d->julian)
822
0
    g_date_update_julian (d);
823
824
0
  g_return_val_if_fail (d->julian, 0);
825
826
  /* Formula taken from the Calendar FAQ; the formula was for the
827
   * Julian Period which starts on 1 January 4713 BC, so we add
828
   * 1,721,425 to the number of days before doing the formula. 
829
   */
830
0
  j  = d->julian_days + 1721425;
831
0
  d4 = (j + 31741 - (j % 7)) % 146097 % 36524 % 1461;
832
0
  L  = d4 / 1460;
833
0
  d1 = ((d4 - L) % 365) + L;
834
0
  w  = d1 / 7 + 1;
835
836
0
  return w;
837
0
}
838
839
/**
840
 * g_date_days_between:
841
 * @date1: the first date
842
 * @date2: the second date
843
 *
844
 * Computes the number of days between two dates.
845
 * If @date2 is prior to @date1, the returned value is negative.
846
 * Both dates must be valid.
847
 *
848
 * Returns: the number of days between @date1 and @date2
849
 */
850
gint
851
g_date_days_between (const GDate *d1,
852
         const GDate *d2)
853
0
{
854
0
  g_return_val_if_fail (g_date_valid (d1), 0);
855
0
  g_return_val_if_fail (g_date_valid (d2), 0);
856
857
0
  return (gint)g_date_get_julian (d2) - (gint)g_date_get_julian (d1);
858
0
}
859
860
/**
861
 * g_date_clear:
862
 * @date: pointer to one or more dates to clear
863
 * @n_dates: number of dates to clear
864
 *
865
 * Initializes one or more #GDate structs to a safe but invalid
866
 * state. The cleared dates will not represent an existing date, but will
867
 * not contain garbage. Useful to init a date declared on the stack.
868
 * Validity can be tested with g_date_valid().
869
 */
870
void         
871
g_date_clear (GDate *d, guint ndates)
872
0
{
873
0
  g_return_if_fail (d != NULL);
874
0
  g_return_if_fail (ndates != 0);
875
  
876
0
  memset (d, 0x0, ndates*sizeof (GDate)); 
877
0
}
878
879
G_LOCK_DEFINE_STATIC (g_date_global);
880
881
/* These are for the parser, output to the user should use *
882
 * g_date_strftime () - this creates more never-freed memory to annoy
883
 * all those memory debugger users. :-) 
884
 */
885
886
static gchar *long_month_names[13] = 
887
{ 
888
  NULL,
889
};
890
891
static gchar *long_month_names_alternative[13] =
892
{
893
  NULL,
894
};
895
896
static gchar *short_month_names[13] = 
897
{
898
  NULL, 
899
};
900
901
static gchar *short_month_names_alternative[13] =
902
{
903
  NULL,
904
};
905
906
/* This tells us if we need to update the parse info */
907
static gchar *current_locale = NULL;
908
909
/* order of these in the current locale */
910
static GDateDMY dmy_order[3] = 
911
{
912
   G_DATE_DAY, G_DATE_MONTH, G_DATE_YEAR
913
};
914
915
/* Where to chop two-digit years: i.e., for the 1930 default, numbers
916
 * 29 and below are counted as in the year 2000, numbers 30 and above
917
 * are counted as in the year 1900.  
918
 */
919
920
static const GDateYear twodigit_start_year = 1930;
921
922
/* It is impossible to enter a year between 1 AD and 99 AD with this
923
 * in effect.  
924
 */
925
static gboolean using_twodigit_years = FALSE;
926
927
/* Adjustment of locale era to AD, non-zero means using locale era
928
 */
929
static gint locale_era_adjust = 0;
930
931
struct _GDateParseTokens {
932
  gint num_ints;
933
  gint n[3];
934
  guint month;
935
};
936
937
typedef struct _GDateParseTokens GDateParseTokens;
938
939
static inline gboolean
940
update_month_match (gsize *longest,
941
                    const gchar *haystack,
942
                    const gchar *needle)
943
0
{
944
0
  gsize length;
945
946
0
  if (needle == NULL)
947
0
    return FALSE;
948
949
0
  length = strlen (needle);
950
0
  if (*longest >= length)
951
0
    return FALSE;
952
953
0
  if (strstr (haystack, needle) == NULL)
954
0
    return FALSE;
955
956
0
  *longest = length;
957
0
  return TRUE;
958
0
}
959
960
0
#define NUM_LEN 10
961
962
/* HOLDS: g_date_global_lock */
963
static void
964
g_date_fill_parse_tokens (const gchar *str, GDateParseTokens *pt)
965
0
{
966
0
  gchar num[4][NUM_LEN+1];
967
0
  gint i;
968
0
  const guchar *s;
969
  
970
  /* We count 4, but store 3; so we can give an error
971
   * if there are 4.
972
   */
973
0
  num[0][0] = num[1][0] = num[2][0] = num[3][0] = '\0';
974
  
975
0
  s = (const guchar *) str;
976
0
  pt->num_ints = 0;
977
0
  while (*s && pt->num_ints < 4) 
978
0
    {
979
      
980
0
      i = 0;
981
0
      while (*s && g_ascii_isdigit (*s) && i < NUM_LEN)
982
0
        {
983
0
          num[pt->num_ints][i] = *s;
984
0
          ++s; 
985
0
          ++i;
986
0
        }
987
      
988
0
      if (i > 0) 
989
0
        {
990
0
          num[pt->num_ints][i] = '\0';
991
0
          ++(pt->num_ints);
992
0
        }
993
      
994
0
      if (*s == '\0') break;
995
      
996
0
      ++s;
997
0
    }
998
  
999
0
  pt->n[0] = pt->num_ints > 0 ? atoi (num[0]) : 0;
1000
0
  pt->n[1] = pt->num_ints > 1 ? atoi (num[1]) : 0;
1001
0
  pt->n[2] = pt->num_ints > 2 ? atoi (num[2]) : 0;
1002
  
1003
0
  pt->month = G_DATE_BAD_MONTH;
1004
  
1005
0
  if (pt->num_ints < 3)
1006
0
    {
1007
0
      gsize longest = 0;
1008
0
      gchar *casefold;
1009
0
      gchar *normalized;
1010
      
1011
0
      casefold = g_utf8_casefold (str, -1);
1012
0
      normalized = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
1013
0
      g_free (casefold);
1014
1015
0
      for (i = 1; i < 13; ++i)
1016
0
        {
1017
          /* Here month names may be in a genitive case if the language
1018
           * grammatical rules require it.
1019
           * Examples of how January may look in some languages:
1020
           * Catalan: "de gener", Croatian: "siječnja", Polish: "stycznia",
1021
           * Upper Sorbian: "januara".
1022
           * Note that most of the languages can't or don't use the the
1023
           * genitive case here so they use nominative everywhere.
1024
           * For example, English always uses "January".
1025
           */
1026
0
          if (update_month_match (&longest, normalized, long_month_names[i]))
1027
0
            pt->month = i;
1028
1029
          /* Here month names will be in a nominative case.
1030
           * Examples of how January may look in some languages:
1031
           * Catalan: "gener", Croatian: "Siječanj", Polish: "styczeń",
1032
           * Upper Sorbian: "Januar".
1033
           */
1034
0
          if (update_month_match (&longest, normalized, long_month_names_alternative[i]))
1035
0
            pt->month = i;
1036
1037
          /* Differences between abbreviated nominative and abbreviated
1038
           * genitive month names are visible in very few languages but
1039
           * let's handle them.
1040
           */
1041
0
          if (update_month_match (&longest, normalized, short_month_names[i]))
1042
0
            pt->month = i;
1043
1044
0
          if (update_month_match (&longest, normalized, short_month_names_alternative[i]))
1045
0
            pt->month = i;
1046
0
        }
1047
1048
0
      g_free (normalized);
1049
0
    }
1050
0
}
1051
1052
/* HOLDS: g_date_global_lock */
1053
static void
1054
g_date_prepare_to_parse (const gchar      *str, 
1055
                         GDateParseTokens *pt)
1056
0
{
1057
0
  const gchar *locale = setlocale (LC_TIME, NULL);
1058
0
  gboolean recompute_localeinfo = FALSE;
1059
0
  GDate d;
1060
  
1061
0
  g_return_if_fail (locale != NULL); /* should not happen */
1062
  
1063
0
  g_date_clear (&d, 1);              /* clear for scratch use */
1064
  
1065
0
  if ( (current_locale == NULL) || (strcmp (locale, current_locale) != 0) ) 
1066
0
    recompute_localeinfo = TRUE;  /* Uh, there used to be a reason for the temporary */
1067
  
1068
0
  if (recompute_localeinfo)
1069
0
    {
1070
0
      int i = 1;
1071
0
      GDateParseTokens testpt;
1072
0
      gchar buf[128];
1073
      
1074
0
      g_free (current_locale); /* still works if current_locale == NULL */
1075
      
1076
0
      current_locale = g_strdup (locale);
1077
      
1078
0
      short_month_names[0] = "Error";
1079
0
      long_month_names[0] = "Error";
1080
1081
0
      while (i < 13) 
1082
0
        {
1083
0
    gchar *casefold;
1084
    
1085
0
          g_date_set_dmy (&d, 1, i, 1976);
1086
    
1087
0
          g_return_if_fail (g_date_valid (&d));
1088
    
1089
0
          g_date_strftime (buf, 127, "%b", &d);
1090
1091
0
    casefold = g_utf8_casefold (buf, -1);
1092
0
          g_free (short_month_names[i]);
1093
0
          short_month_names[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
1094
0
    g_free (casefold);
1095
    
1096
0
          g_date_strftime (buf, 127, "%B", &d);
1097
0
    casefold = g_utf8_casefold (buf, -1);
1098
0
          g_free (long_month_names[i]);
1099
0
          long_month_names[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
1100
0
    g_free (casefold);
1101
          
1102
0
          g_date_strftime (buf, 127, "%Ob", &d);
1103
0
          casefold = g_utf8_casefold (buf, -1);
1104
0
          g_free (short_month_names_alternative[i]);
1105
0
          short_month_names_alternative[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
1106
0
          g_free (casefold);
1107
1108
0
          g_date_strftime (buf, 127, "%OB", &d);
1109
0
          casefold = g_utf8_casefold (buf, -1);
1110
0
          g_free (long_month_names_alternative[i]);
1111
0
          long_month_names_alternative[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
1112
0
          g_free (casefold);
1113
1114
0
          ++i;
1115
0
        }
1116
      
1117
      /* Determine DMY order */
1118
      
1119
      /* had to pick a random day - don't change this, some strftimes
1120
       * are broken on some days, and this one is good so far. */
1121
0
      g_date_set_dmy (&d, 4, 7, 1976);
1122
      
1123
0
      g_date_strftime (buf, 127, "%x", &d);
1124
      
1125
0
      g_date_fill_parse_tokens (buf, &testpt);
1126
1127
0
      using_twodigit_years = FALSE;
1128
0
      locale_era_adjust = 0;
1129
0
      dmy_order[0] = G_DATE_DAY;
1130
0
      dmy_order[1] = G_DATE_MONTH;
1131
0
      dmy_order[2] = G_DATE_YEAR;
1132
      
1133
0
      i = 0;
1134
0
      while (i < testpt.num_ints)
1135
0
        {
1136
0
          switch (testpt.n[i])
1137
0
            {
1138
0
            case 7:
1139
0
              dmy_order[i] = G_DATE_MONTH;
1140
0
              break;
1141
0
            case 4:
1142
0
              dmy_order[i] = G_DATE_DAY;
1143
0
              break;
1144
0
            case 76:
1145
0
              using_twodigit_years = TRUE;
1146
0
              G_GNUC_FALLTHROUGH;
1147
0
            case 1976:
1148
0
              dmy_order[i] = G_DATE_YEAR;
1149
0
              break;
1150
0
            default:
1151
              /* assume locale era */
1152
0
              locale_era_adjust = 1976 - testpt.n[i];
1153
0
              dmy_order[i] = G_DATE_YEAR;
1154
0
              break;
1155
0
            }
1156
0
          ++i;
1157
0
        }
1158
      
1159
#if defined(G_ENABLE_DEBUG) && 0
1160
      DEBUG_MSG (("**GDate prepared a new set of locale-specific parse rules."));
1161
      i = 1;
1162
      while (i < 13) 
1163
        {
1164
          DEBUG_MSG (("  %s   %s", long_month_names[i], short_month_names[i]));
1165
          ++i;
1166
        }
1167
      DEBUG_MSG (("Alternative month names:"));
1168
      i = 1;
1169
      while (i < 13)
1170
        {
1171
          DEBUG_MSG (("  %s   %s", long_month_names_alternative[i], short_month_names_alternative[i]));
1172
          ++i;
1173
        }
1174
      if (using_twodigit_years)
1175
        {
1176
    DEBUG_MSG (("**Using twodigit years with cutoff year: %u", twodigit_start_year));
1177
        }
1178
      { 
1179
        gchar *strings[3];
1180
        i = 0;
1181
        while (i < 3)
1182
          {
1183
            switch (dmy_order[i])
1184
              {
1185
              case G_DATE_MONTH:
1186
                strings[i] = "Month";
1187
                break;
1188
              case G_DATE_YEAR:
1189
                strings[i] = "Year";
1190
                break;
1191
              case G_DATE_DAY:
1192
                strings[i] = "Day";
1193
                break;
1194
              default:
1195
                strings[i] = NULL;
1196
                break;
1197
              }
1198
            ++i;
1199
          }
1200
        DEBUG_MSG (("**Order: %s, %s, %s", strings[0], strings[1], strings[2]));
1201
        DEBUG_MSG (("**Sample date in this locale: '%s'", buf));
1202
      }
1203
#endif
1204
0
    }
1205
  
1206
0
  g_date_fill_parse_tokens (str, pt);
1207
0
}
1208
1209
static guint
1210
convert_twodigit_year (guint y)
1211
0
{
1212
0
  if (using_twodigit_years && y < 100)
1213
0
    {
1214
0
      guint two     =  twodigit_start_year % 100;
1215
0
      guint century = (twodigit_start_year / 100) * 100;
1216
1217
0
      if (y < two)
1218
0
        century += 100;
1219
1220
0
      y += century;
1221
0
    }
1222
0
  return y;
1223
0
}
1224
1225
/**
1226
 * g_date_set_parse:
1227
 * @date: a #GDate to fill in
1228
 * @str: string to parse
1229
 *
1230
 * Parses a user-inputted string @str, and try to figure out what date it
1231
 * represents, taking the [current locale](running.html#locale)
1232
 * into account. If the string is successfully parsed, the date will be
1233
 * valid after the call. Otherwise, it will be invalid. You should check
1234
 * using g_date_valid() to see whether the parsing succeeded.
1235
 *
1236
 * This function is not appropriate for file formats and the like; it
1237
 * isn't very precise, and its exact behavior varies with the locale.
1238
 * It's intended to be a heuristic routine that guesses what the user
1239
 * means by a given string (and it does work pretty well in that
1240
 * capacity).
1241
 */
1242
void         
1243
g_date_set_parse (GDate       *d, 
1244
                  const gchar *str)
1245
0
{
1246
0
  GDateParseTokens pt;
1247
0
  guint m = G_DATE_BAD_MONTH, day = G_DATE_BAD_DAY, y = G_DATE_BAD_YEAR;
1248
0
  gsize str_len;
1249
  
1250
0
  g_return_if_fail (d != NULL);
1251
  
1252
  /* set invalid */
1253
0
  g_date_clear (d, 1);
1254
1255
  /* Anything longer than this is ridiculous and could take a while to normalize.
1256
   * This limit is chosen arbitrarily. */
1257
0
  str_len = strlen (str);
1258
0
  if (str_len > 200)
1259
0
    return;
1260
1261
  /* The input has to be valid UTF-8. */
1262
0
  if (!g_utf8_validate_len (str, str_len, NULL))
1263
0
    return;
1264
1265
0
  G_LOCK (g_date_global);
1266
1267
0
  g_date_prepare_to_parse (str, &pt);
1268
  
1269
0
  DEBUG_MSG (("Found %d ints, '%d' '%d' '%d' and written out month %d",
1270
0
        pt.num_ints, pt.n[0], pt.n[1], pt.n[2], pt.month));
1271
  
1272
  
1273
0
  if (pt.num_ints == 4) 
1274
0
    {
1275
0
      G_UNLOCK (g_date_global);
1276
0
      return; /* presumably a typo; bail out. */
1277
0
    }
1278
  
1279
0
  if (pt.num_ints > 1)
1280
0
    {
1281
0
      int i = 0;
1282
0
      int j = 0;
1283
      
1284
0
      g_assert (pt.num_ints < 4); /* i.e., it is 2 or 3 */
1285
      
1286
0
      while (i < pt.num_ints && j < 3) 
1287
0
        {
1288
0
          switch (dmy_order[j])
1289
0
            {
1290
0
            case G_DATE_MONTH:
1291
0
      {
1292
0
        if (pt.num_ints == 2 && pt.month != G_DATE_BAD_MONTH)
1293
0
    {
1294
0
      m = pt.month;
1295
0
      ++j;      /* skip months, but don't skip this number */
1296
0
      continue;
1297
0
    }
1298
0
        else 
1299
0
    m = pt.n[i];
1300
0
      }
1301
0
      break;
1302
0
            case G_DATE_DAY:
1303
0
      {
1304
0
        if (pt.num_ints == 2 && pt.month == G_DATE_BAD_MONTH)
1305
0
    {
1306
0
      day = 1;
1307
0
      ++j;      /* skip days, since we may have month/year */
1308
0
      continue;
1309
0
    }
1310
0
        day = pt.n[i];
1311
0
      }
1312
0
      break;
1313
0
            case G_DATE_YEAR:
1314
0
      {
1315
0
        y  = pt.n[i];
1316
        
1317
0
        if (locale_era_adjust != 0)
1318
0
          {
1319
0
      y += locale_era_adjust;
1320
0
          }
1321
1322
0
        y = convert_twodigit_year (y);
1323
0
      }
1324
0
      break;
1325
0
            default:
1326
0
              break;
1327
0
            }
1328
    
1329
0
          ++i;
1330
0
          ++j;
1331
0
        }
1332
      
1333
      
1334
0
      if (pt.num_ints == 3 && !g_date_valid_dmy (day, m, y))
1335
0
        {
1336
          /* Try YYYY MM DD */
1337
0
          y   = pt.n[0];
1338
0
          m   = pt.n[1];
1339
0
          day = pt.n[2];
1340
          
1341
0
          if (using_twodigit_years && y < 100) 
1342
0
            y = G_DATE_BAD_YEAR; /* avoids ambiguity */
1343
0
        }
1344
0
      else if (pt.num_ints == 2)
1345
0
  {
1346
0
    if (m == G_DATE_BAD_MONTH && pt.month != G_DATE_BAD_MONTH)
1347
0
      m = pt.month;
1348
0
  }
1349
0
    }
1350
0
  else if (pt.num_ints == 1) 
1351
0
    {
1352
0
      if (pt.month != G_DATE_BAD_MONTH)
1353
0
        {
1354
          /* Month name and year? */
1355
0
          m    = pt.month;
1356
0
          day  = 1;
1357
0
          y = pt.n[0];
1358
0
        }
1359
0
      else
1360
0
        {
1361
          /* Try yyyymmdd and yymmdd */
1362
    
1363
0
          m   = (pt.n[0]/100) % 100;
1364
0
          day = pt.n[0] % 100;
1365
0
          y   = pt.n[0]/10000;
1366
1367
0
          y   = convert_twodigit_year (y);
1368
0
        }
1369
0
    }
1370
  
1371
  /* See if we got anything valid out of all this. */
1372
  /* y < 8000 is to catch 19998 style typos; the library is OK up to 65535 or so */
1373
0
  if (y < 8000 && g_date_valid_dmy (day, m, y)) 
1374
0
    {
1375
0
      d->month = m;
1376
0
      d->day   = day;
1377
0
      d->year  = y;
1378
0
      d->dmy   = TRUE;
1379
0
    }
1380
0
#ifdef G_ENABLE_DEBUG
1381
0
  else 
1382
0
    {
1383
0
      DEBUG_MSG (("Rejected DMY %u %u %u", day, m, y));
1384
0
    }
1385
0
#endif
1386
0
  G_UNLOCK (g_date_global);
1387
0
}
1388
1389
gboolean
1390
_g_localtime (time_t timet, struct tm *out_tm)
1391
0
{
1392
0
  gboolean success = TRUE;
1393
1394
0
#ifdef HAVE_LOCALTIME_R
1395
0
  tzset ();
1396
0
  if (!localtime_r (&timet, out_tm))
1397
0
    success = FALSE;
1398
#else
1399
  {
1400
    struct tm *ptm = localtime (&timet);
1401
1402
    if (ptm == NULL)
1403
      {
1404
        /* Happens at least in Microsoft's C library if you pass a
1405
         * negative time_t.
1406
         */
1407
        success = FALSE;
1408
      }
1409
    else
1410
      memcpy (out_tm, ptm, sizeof (struct tm));
1411
  }
1412
#endif
1413
1414
0
  return success;
1415
0
}
1416
1417
/**
1418
 * g_date_set_time_t:
1419
 * @date: a #GDate 
1420
 * @timet: time_t value to set
1421
 *
1422
 * Sets the value of a date to the date corresponding to a time 
1423
 * specified as a time_t. The time to date conversion is done using 
1424
 * the user's current timezone.
1425
 *
1426
 * To set the value of a date to the current day, you could write:
1427
 * |[<!-- language="C" -->
1428
 *  time_t now = time (NULL);
1429
 *  if (now == (time_t) -1)
1430
 *    // handle the error
1431
 *  g_date_set_time_t (date, now);
1432
 * ]|
1433
 *
1434
 * Since: 2.10
1435
 */
1436
void         
1437
g_date_set_time_t (GDate *date,
1438
       time_t timet)
1439
0
{
1440
0
  struct tm tm;
1441
0
  gboolean success;
1442
1443
0
  g_return_if_fail (date != NULL);
1444
1445
0
  success = _g_localtime (timet, &tm);
1446
0
  if (!success)
1447
0
    {
1448
      /* Still set a default date, 2000-01-01.
1449
       *
1450
       * We may assert out below. */
1451
0
      tm.tm_mon = 0;
1452
0
      tm.tm_mday = 1;
1453
0
      tm.tm_year = 100;
1454
0
    }
1455
1456
0
  date->julian = FALSE;
1457
  
1458
0
  date->month = tm.tm_mon + 1;
1459
0
  date->day   = tm.tm_mday;
1460
0
  date->year  = tm.tm_year + 1900;
1461
  
1462
0
  g_return_if_fail (g_date_valid_dmy (date->day, date->month, date->year));
1463
  
1464
0
  date->dmy    = TRUE;
1465
1466
0
#ifndef G_DISABLE_CHECKS
1467
0
  if (!success)
1468
0
    g_return_if_fail_warning (G_LOG_DOMAIN, "g_date_set_time", "localtime() == NULL");
1469
0
#endif
1470
0
}
1471
1472
1473
/**
1474
 * g_date_set_time:
1475
 * @date: a #GDate.
1476
 * @time_: #GTime value to set.
1477
 *
1478
 * Sets the value of a date from a #GTime value.
1479
 * The time to date conversion is done using the user's current timezone.
1480
 *
1481
 * Deprecated: 2.10: Use g_date_set_time_t() instead.
1482
 */
1483
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
1484
void
1485
g_date_set_time (GDate *date,
1486
     GTime  time_)
1487
0
{
1488
0
  g_date_set_time_t (date, (time_t) time_);
1489
0
}
1490
G_GNUC_END_IGNORE_DEPRECATIONS
1491
1492
/**
1493
 * g_date_set_time_val:
1494
 * @date: a #GDate 
1495
 * @timeval: #GTimeVal value to set
1496
 *
1497
 * Sets the value of a date from a #GTimeVal value.  Note that the
1498
 * @tv_usec member is ignored, because #GDate can't make use of the
1499
 * additional precision.
1500
 *
1501
 * The time to date conversion is done using the user's current timezone.
1502
 *
1503
 * Since: 2.10
1504
 * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use g_date_set_time_t()
1505
 *    instead.
1506
 */
1507
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
1508
void
1509
g_date_set_time_val (GDate    *date,
1510
         GTimeVal *timeval)
1511
0
{
1512
0
  g_date_set_time_t (date, (time_t) timeval->tv_sec);
1513
0
}
1514
G_GNUC_END_IGNORE_DEPRECATIONS
1515
1516
/**
1517
 * g_date_set_month:
1518
 * @date: a #GDate
1519
 * @month: month to set
1520
 *
1521
 * Sets the month of the year for a #GDate.  If the resulting
1522
 * day-month-year triplet is invalid, the date will be invalid.
1523
 */
1524
void         
1525
g_date_set_month (GDate     *d, 
1526
                  GDateMonth m)
1527
0
{
1528
0
  g_return_if_fail (d != NULL);
1529
0
  g_return_if_fail (g_date_valid_month (m));
1530
1531
0
  if (d->julian && !d->dmy) g_date_update_dmy(d);
1532
0
  d->julian = FALSE;
1533
  
1534
0
  d->month = m;
1535
  
1536
0
  if (g_date_valid_dmy (d->day, d->month, d->year))
1537
0
    d->dmy = TRUE;
1538
0
  else 
1539
0
    d->dmy = FALSE;
1540
0
}
1541
1542
/**
1543
 * g_date_set_day:
1544
 * @date: a #GDate
1545
 * @day: day to set
1546
 *
1547
 * Sets the day of the month for a #GDate. If the resulting
1548
 * day-month-year triplet is invalid, the date will be invalid.
1549
 */
1550
void         
1551
g_date_set_day (GDate    *d, 
1552
                GDateDay  day)
1553
0
{
1554
0
  g_return_if_fail (d != NULL);
1555
0
  g_return_if_fail (g_date_valid_day (day));
1556
  
1557
0
  if (d->julian && !d->dmy) g_date_update_dmy(d);
1558
0
  d->julian = FALSE;
1559
  
1560
0
  d->day = day;
1561
  
1562
0
  if (g_date_valid_dmy (d->day, d->month, d->year))
1563
0
    d->dmy = TRUE;
1564
0
  else 
1565
0
    d->dmy = FALSE;
1566
0
}
1567
1568
/**
1569
 * g_date_set_year:
1570
 * @date: a #GDate
1571
 * @year: year to set
1572
 *
1573
 * Sets the year for a #GDate. If the resulting day-month-year
1574
 * triplet is invalid, the date will be invalid.
1575
 */
1576
void         
1577
g_date_set_year (GDate     *d, 
1578
                 GDateYear  y)
1579
0
{
1580
0
  g_return_if_fail (d != NULL);
1581
0
  g_return_if_fail (g_date_valid_year (y));
1582
  
1583
0
  if (d->julian && !d->dmy) g_date_update_dmy(d);
1584
0
  d->julian = FALSE;
1585
  
1586
0
  d->year = y;
1587
  
1588
0
  if (g_date_valid_dmy (d->day, d->month, d->year))
1589
0
    d->dmy = TRUE;
1590
0
  else 
1591
0
    d->dmy = FALSE;
1592
0
}
1593
1594
/**
1595
 * g_date_set_dmy:
1596
 * @date: a #GDate
1597
 * @day: day
1598
 * @month: month
1599
 * @y: year
1600
 *
1601
 * Sets the value of a #GDate from a day, month, and year.
1602
 * The day-month-year triplet must be valid; if you aren't
1603
 * sure it is, call g_date_valid_dmy() to check before you
1604
 * set it.
1605
 */
1606
void         
1607
g_date_set_dmy (GDate      *d, 
1608
                GDateDay    day, 
1609
                GDateMonth  m, 
1610
                GDateYear   y)
1611
0
{
1612
0
  g_return_if_fail (d != NULL);
1613
0
  g_return_if_fail (g_date_valid_dmy (day, m, y));
1614
  
1615
0
  d->julian = FALSE;
1616
  
1617
0
  d->month = m;
1618
0
  d->day   = day;
1619
0
  d->year  = y;
1620
  
1621
0
  d->dmy = TRUE;
1622
0
}
1623
1624
/**
1625
 * g_date_set_julian:
1626
 * @date: a #GDate
1627
 * @julian_date: Julian day number (days since January 1, Year 1)
1628
 *
1629
 * Sets the value of a #GDate from a Julian day number.
1630
 */
1631
void         
1632
g_date_set_julian (GDate   *d, 
1633
                   guint32  j)
1634
0
{
1635
0
  g_return_if_fail (d != NULL);
1636
0
  g_return_if_fail (g_date_valid_julian (j));
1637
  
1638
0
  d->julian_days = j;
1639
0
  d->julian = TRUE;
1640
0
  d->dmy = FALSE;
1641
0
}
1642
1643
/**
1644
 * g_date_is_first_of_month:
1645
 * @date: a #GDate to check
1646
 *
1647
 * Returns %TRUE if the date is on the first of a month.
1648
 * The date must be valid.
1649
 *
1650
 * Returns: %TRUE if the date is the first of the month
1651
 */
1652
gboolean     
1653
g_date_is_first_of_month (const GDate *d)
1654
0
{
1655
0
  g_return_val_if_fail (g_date_valid (d), FALSE);
1656
  
1657
0
  if (!d->dmy) 
1658
0
    g_date_update_dmy (d);
1659
1660
0
  g_return_val_if_fail (d->dmy, FALSE);  
1661
  
1662
0
  if (d->day == 1) return TRUE;
1663
0
  else return FALSE;
1664
0
}
1665
1666
/**
1667
 * g_date_is_last_of_month:
1668
 * @date: a #GDate to check
1669
 *
1670
 * Returns %TRUE if the date is the last day of the month.
1671
 * The date must be valid.
1672
 *
1673
 * Returns: %TRUE if the date is the last day of the month
1674
 */
1675
gboolean     
1676
g_date_is_last_of_month (const GDate *d)
1677
0
{
1678
0
  gint idx;
1679
  
1680
0
  g_return_val_if_fail (g_date_valid (d), FALSE);
1681
  
1682
0
  if (!d->dmy) 
1683
0
    g_date_update_dmy (d);
1684
1685
0
  g_return_val_if_fail (d->dmy, FALSE);  
1686
  
1687
0
  idx = g_date_is_leap_year (d->year) ? 1 : 0;
1688
  
1689
0
  if (d->day == days_in_months[idx][d->month]) return TRUE;
1690
0
  else return FALSE;
1691
0
}
1692
1693
/**
1694
 * g_date_add_days:
1695
 * @date: a #GDate to increment
1696
 * @n_days: number of days to move the date forward
1697
 *
1698
 * Increments a date some number of days.
1699
 * To move forward by weeks, add weeks*7 days.
1700
 * The date must be valid.
1701
 */
1702
void         
1703
g_date_add_days (GDate *d, 
1704
                 guint  ndays)
1705
0
{
1706
0
  g_return_if_fail (g_date_valid (d));
1707
  
1708
0
  if (!d->julian)
1709
0
    g_date_update_julian (d);
1710
1711
0
  g_return_if_fail (d->julian);
1712
0
  g_return_if_fail (ndays <= G_MAXUINT32 - d->julian_days);
1713
  
1714
0
  d->julian_days += ndays;
1715
0
  d->dmy = FALSE;
1716
0
}
1717
1718
/**
1719
 * g_date_subtract_days:
1720
 * @date: a #GDate to decrement
1721
 * @n_days: number of days to move
1722
 *
1723
 * Moves a date some number of days into the past.
1724
 * To move by weeks, just move by weeks*7 days.
1725
 * The date must be valid.
1726
 */
1727
void         
1728
g_date_subtract_days (GDate *d, 
1729
                      guint  ndays)
1730
0
{
1731
0
  g_return_if_fail (g_date_valid (d));
1732
  
1733
0
  if (!d->julian)
1734
0
    g_date_update_julian (d);
1735
1736
0
  g_return_if_fail (d->julian);
1737
0
  g_return_if_fail (d->julian_days > ndays);
1738
  
1739
0
  d->julian_days -= ndays;
1740
0
  d->dmy = FALSE;
1741
0
}
1742
1743
/**
1744
 * g_date_add_months:
1745
 * @date: a #GDate to increment
1746
 * @n_months: number of months to move forward
1747
 *
1748
 * Increments a date by some number of months.
1749
 * If the day of the month is greater than 28,
1750
 * this routine may change the day of the month
1751
 * (because the destination month may not have
1752
 * the current day in it). The date must be valid.
1753
 */
1754
void         
1755
g_date_add_months (GDate *d, 
1756
                   guint  nmonths)
1757
0
{
1758
0
  guint years, months;
1759
0
  gint idx;
1760
  
1761
0
  g_return_if_fail (g_date_valid (d));
1762
  
1763
0
  if (!d->dmy) 
1764
0
    g_date_update_dmy (d);
1765
1766
0
  g_return_if_fail (d->dmy != 0);
1767
0
  g_return_if_fail (nmonths <= G_MAXUINT - (d->month - 1));
1768
1769
0
  nmonths += d->month - 1;
1770
  
1771
0
  years  = nmonths/12;
1772
0
  months = nmonths%12;
1773
1774
0
  g_return_if_fail (years <= (guint) (G_MAXUINT16 - d->year));
1775
1776
0
  d->month = months + 1;
1777
0
  d->year  += years;
1778
  
1779
0
  idx = g_date_is_leap_year (d->year) ? 1 : 0;
1780
  
1781
0
  if (d->day > days_in_months[idx][d->month])
1782
0
    d->day = days_in_months[idx][d->month];
1783
  
1784
0
  d->julian = FALSE;
1785
  
1786
0
  g_return_if_fail (g_date_valid (d));
1787
0
}
1788
1789
/**
1790
 * g_date_subtract_months:
1791
 * @date: a #GDate to decrement
1792
 * @n_months: number of months to move
1793
 *
1794
 * Moves a date some number of months into the past.
1795
 * If the current day of the month doesn't exist in
1796
 * the destination month, the day of the month
1797
 * may change. The date must be valid.
1798
 */
1799
void         
1800
g_date_subtract_months (GDate *d, 
1801
                        guint  nmonths)
1802
0
{
1803
0
  guint years, months;
1804
0
  gint idx;
1805
  
1806
0
  g_return_if_fail (g_date_valid (d));
1807
  
1808
0
  if (!d->dmy) 
1809
0
    g_date_update_dmy (d);
1810
1811
0
  g_return_if_fail (d->dmy != 0);
1812
  
1813
0
  years  = nmonths/12;
1814
0
  months = nmonths%12;
1815
  
1816
0
  g_return_if_fail (d->year > years);
1817
  
1818
0
  d->year  -= years;
1819
  
1820
0
  if (d->month > months) d->month -= months;
1821
0
  else 
1822
0
    {
1823
0
      months -= d->month;
1824
0
      d->month = 12 - months;
1825
0
      d->year -= 1;
1826
0
    }
1827
  
1828
0
  idx = g_date_is_leap_year (d->year) ? 1 : 0;
1829
  
1830
0
  if (d->day > days_in_months[idx][d->month])
1831
0
    d->day = days_in_months[idx][d->month];
1832
  
1833
0
  d->julian = FALSE;
1834
  
1835
0
  g_return_if_fail (g_date_valid (d));
1836
0
}
1837
1838
/**
1839
 * g_date_add_years:
1840
 * @date: a #GDate to increment
1841
 * @n_years: number of years to move forward
1842
 *
1843
 * Increments a date by some number of years.
1844
 * If the date is February 29, and the destination
1845
 * year is not a leap year, the date will be changed
1846
 * to February 28. The date must be valid.
1847
 */
1848
void         
1849
g_date_add_years (GDate *d, 
1850
                  guint  nyears)
1851
0
{
1852
0
  g_return_if_fail (g_date_valid (d));
1853
  
1854
0
  if (!d->dmy) 
1855
0
    g_date_update_dmy (d);
1856
1857
0
  g_return_if_fail (d->dmy != 0);
1858
0
  g_return_if_fail (nyears <= (guint) (G_MAXUINT16 - d->year));
1859
1860
0
  d->year += nyears;
1861
  
1862
0
  if (d->month == 2 && d->day == 29)
1863
0
    {
1864
0
      if (!g_date_is_leap_year (d->year))
1865
0
        d->day = 28;
1866
0
    }
1867
  
1868
0
  d->julian = FALSE;
1869
0
}
1870
1871
/**
1872
 * g_date_subtract_years:
1873
 * @date: a #GDate to decrement
1874
 * @n_years: number of years to move
1875
 *
1876
 * Moves a date some number of years into the past.
1877
 * If the current day doesn't exist in the destination
1878
 * year (i.e. it's February 29 and you move to a non-leap-year)
1879
 * then the day is changed to February 29. The date
1880
 * must be valid.
1881
 */
1882
void         
1883
g_date_subtract_years (GDate *d, 
1884
                       guint  nyears)
1885
0
{
1886
0
  g_return_if_fail (g_date_valid (d));
1887
  
1888
0
  if (!d->dmy) 
1889
0
    g_date_update_dmy (d);
1890
1891
0
  g_return_if_fail (d->dmy != 0);
1892
0
  g_return_if_fail (d->year > nyears);
1893
  
1894
0
  d->year -= nyears;
1895
  
1896
0
  if (d->month == 2 && d->day == 29)
1897
0
    {
1898
0
      if (!g_date_is_leap_year (d->year))
1899
0
        d->day = 28;
1900
0
    }
1901
  
1902
0
  d->julian = FALSE;
1903
0
}
1904
1905
/**
1906
 * g_date_is_leap_year:
1907
 * @year: year to check
1908
 *
1909
 * Returns %TRUE if the year is a leap year.
1910
 *
1911
 * For the purposes of this function, leap year is every year
1912
 * divisible by 4 unless that year is divisible by 100. If it
1913
 * is divisible by 100 it would be a leap year only if that year
1914
 * is also divisible by 400.
1915
 *
1916
 * Returns: %TRUE if the year is a leap year
1917
 */
1918
gboolean     
1919
g_date_is_leap_year (GDateYear year)
1920
0
{
1921
0
  g_return_val_if_fail (g_date_valid_year (year), FALSE);
1922
  
1923
0
  return ( (((year % 4) == 0) && ((year % 100) != 0)) ||
1924
0
           (year % 400) == 0 );
1925
0
}
1926
1927
/**
1928
 * g_date_get_days_in_month:
1929
 * @month: month
1930
 * @year: year
1931
 *
1932
 * Returns the number of days in a month, taking leap
1933
 * years into account.
1934
 *
1935
 * Returns: number of days in @month during the @year
1936
 */
1937
guint8         
1938
g_date_get_days_in_month (GDateMonth month, 
1939
                          GDateYear  year)
1940
0
{
1941
0
  gint idx;
1942
  
1943
0
  g_return_val_if_fail (g_date_valid_year (year), 0);
1944
0
  g_return_val_if_fail (g_date_valid_month (month), 0);
1945
  
1946
0
  idx = g_date_is_leap_year (year) ? 1 : 0;
1947
  
1948
0
  return days_in_months[idx][month];
1949
0
}
1950
1951
/**
1952
 * g_date_get_monday_weeks_in_year:
1953
 * @year: a year
1954
 *
1955
 * Returns the number of weeks in the year, where weeks
1956
 * are taken to start on Monday. Will be 52 or 53. The
1957
 * date must be valid. (Years always have 52 7-day periods,
1958
 * plus 1 or 2 extra days depending on whether it's a leap
1959
 * year. This function is basically telling you how many
1960
 * Mondays are in the year, i.e. there are 53 Mondays if
1961
 * one of the extra days happens to be a Monday.)
1962
 *
1963
 * Returns: number of Mondays in the year
1964
 */
1965
guint8       
1966
g_date_get_monday_weeks_in_year (GDateYear year)
1967
0
{
1968
0
  GDate d;
1969
  
1970
0
  g_return_val_if_fail (g_date_valid_year (year), 0);
1971
  
1972
0
  g_date_clear (&d, 1);
1973
0
  g_date_set_dmy (&d, 1, 1, year);
1974
0
  if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1975
0
  g_date_set_dmy (&d, 31, 12, year);
1976
0
  if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1977
0
  if (g_date_is_leap_year (year)) 
1978
0
    {
1979
0
      g_date_set_dmy (&d, 2, 1, year);
1980
0
      if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1981
0
      g_date_set_dmy (&d, 30, 12, year);
1982
0
      if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1983
0
    }
1984
0
  return 52;
1985
0
}
1986
1987
/**
1988
 * g_date_get_sunday_weeks_in_year:
1989
 * @year: year to count weeks in
1990
 *
1991
 * Returns the number of weeks in the year, where weeks
1992
 * are taken to start on Sunday. Will be 52 or 53. The
1993
 * date must be valid. (Years always have 52 7-day periods,
1994
 * plus 1 or 2 extra days depending on whether it's a leap
1995
 * year. This function is basically telling you how many
1996
 * Sundays are in the year, i.e. there are 53 Sundays if
1997
 * one of the extra days happens to be a Sunday.)
1998
 *
1999
 * Returns: the number of weeks in @year
2000
 */
2001
guint8       
2002
g_date_get_sunday_weeks_in_year (GDateYear year)
2003
0
{
2004
0
  GDate d;
2005
  
2006
0
  g_return_val_if_fail (g_date_valid_year (year), 0);
2007
  
2008
0
  g_date_clear (&d, 1);
2009
0
  g_date_set_dmy (&d, 1, 1, year);
2010
0
  if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
2011
0
  g_date_set_dmy (&d, 31, 12, year);
2012
0
  if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
2013
0
  if (g_date_is_leap_year (year)) 
2014
0
    {
2015
0
      g_date_set_dmy (&d, 2, 1, year);
2016
0
      if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
2017
0
      g_date_set_dmy (&d, 30, 12, year);
2018
0
      if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
2019
0
    }
2020
0
  return 52;
2021
0
}
2022
2023
/**
2024
 * g_date_compare:
2025
 * @lhs: first date to compare
2026
 * @rhs: second date to compare
2027
 *
2028
 * qsort()-style comparison function for dates.
2029
 * Both dates must be valid.
2030
 *
2031
 * Returns: 0 for equal, less than zero if @lhs is less than @rhs,
2032
 *     greater than zero if @lhs is greater than @rhs
2033
 */
2034
gint         
2035
g_date_compare (const GDate *lhs, 
2036
                const GDate *rhs)
2037
0
{
2038
0
  g_return_val_if_fail (lhs != NULL, 0);
2039
0
  g_return_val_if_fail (rhs != NULL, 0);
2040
0
  g_return_val_if_fail (g_date_valid (lhs), 0);
2041
0
  g_return_val_if_fail (g_date_valid (rhs), 0);
2042
  
2043
  /* Remember the self-comparison case! I think it works right now. */
2044
  
2045
0
  while (TRUE)
2046
0
    {
2047
0
      if (lhs->julian && rhs->julian) 
2048
0
        {
2049
0
          if (lhs->julian_days < rhs->julian_days) return -1;
2050
0
          else if (lhs->julian_days > rhs->julian_days) return 1;
2051
0
          else                                          return 0;
2052
0
        }
2053
0
      else if (lhs->dmy && rhs->dmy) 
2054
0
        {
2055
0
          if (lhs->year < rhs->year)               return -1;
2056
0
          else if (lhs->year > rhs->year)               return 1;
2057
0
          else 
2058
0
            {
2059
0
              if (lhs->month < rhs->month)         return -1;
2060
0
              else if (lhs->month > rhs->month)         return 1;
2061
0
              else 
2062
0
                {
2063
0
                  if (lhs->day < rhs->day)              return -1;
2064
0
                  else if (lhs->day > rhs->day)              return 1;
2065
0
                  else                                       return 0;
2066
0
                }
2067
              
2068
0
            }
2069
          
2070
0
        }
2071
0
      else
2072
0
        {
2073
0
          if (!lhs->julian) g_date_update_julian (lhs);
2074
0
          if (!rhs->julian) g_date_update_julian (rhs);
2075
0
          g_return_val_if_fail (lhs->julian, 0);
2076
0
          g_return_val_if_fail (rhs->julian, 0);
2077
0
        }
2078
      
2079
0
    }
2080
0
  return 0; /* warnings */
2081
0
}
2082
2083
/**
2084
 * g_date_to_struct_tm:
2085
 * @date: a #GDate to set the struct tm from
2086
 * @tm: (not nullable): struct tm to fill
2087
 *
2088
 * Fills in the date-related bits of a struct tm using the @date value.
2089
 * Initializes the non-date parts with something safe but meaningless.
2090
 */
2091
void        
2092
g_date_to_struct_tm (const GDate *d, 
2093
                     struct tm   *tm)
2094
0
{
2095
0
  GDateWeekday day;
2096
     
2097
0
  g_return_if_fail (g_date_valid (d));
2098
0
  g_return_if_fail (tm != NULL);
2099
  
2100
0
  if (!d->dmy) 
2101
0
    g_date_update_dmy (d);
2102
2103
0
  g_return_if_fail (d->dmy != 0);
2104
  
2105
  /* zero all the irrelevant fields to be sure they're valid */
2106
  
2107
  /* On Linux and maybe other systems, there are weird non-POSIX
2108
   * fields on the end of struct tm that choke strftime if they
2109
   * contain garbage.  So we need to 0 the entire struct, not just the
2110
   * fields we know to exist. 
2111
   */
2112
  
2113
0
  memset (tm, 0x0, sizeof (struct tm));
2114
  
2115
0
  tm->tm_mday = d->day;
2116
0
  tm->tm_mon  = d->month - 1; /* 0-11 goes in tm */
2117
0
  tm->tm_year = ((int)d->year) - 1900; /* X/Open says tm_year can be negative */
2118
  
2119
0
  day = g_date_get_weekday (d);
2120
0
  if (day == 7) day = 0; /* struct tm wants days since Sunday, so Sunday is 0 */
2121
  
2122
0
  tm->tm_wday = (int)day;
2123
  
2124
0
  tm->tm_yday = g_date_get_day_of_year (d) - 1; /* 0 to 365 */
2125
0
  tm->tm_isdst = -1; /* -1 means "information not available" */
2126
0
}
2127
2128
/**
2129
 * g_date_clamp:
2130
 * @date: a #GDate to clamp
2131
 * @min_date: minimum accepted value for @date
2132
 * @max_date: maximum accepted value for @date
2133
 *
2134
 * If @date is prior to @min_date, sets @date equal to @min_date.
2135
 * If @date falls after @max_date, sets @date equal to @max_date.
2136
 * Otherwise, @date is unchanged.
2137
 * Either of @min_date and @max_date may be %NULL.
2138
 * All non-%NULL dates must be valid.
2139
 */
2140
void
2141
g_date_clamp (GDate       *date,
2142
        const GDate *min_date,
2143
        const GDate *max_date)
2144
0
{
2145
0
  g_return_if_fail (g_date_valid (date));
2146
2147
0
  if (min_date != NULL)
2148
0
    g_return_if_fail (g_date_valid (min_date));
2149
2150
0
  if (max_date != NULL)
2151
0
    g_return_if_fail (g_date_valid (max_date));
2152
2153
0
  if (min_date != NULL && max_date != NULL)
2154
0
    g_return_if_fail (g_date_compare (min_date, max_date) <= 0);
2155
2156
0
  if (min_date && g_date_compare (date, min_date) < 0)
2157
0
    *date = *min_date;
2158
2159
0
  if (max_date && g_date_compare (max_date, date) < 0)
2160
0
    *date = *max_date;
2161
0
}
2162
2163
/**
2164
 * g_date_order:
2165
 * @date1: the first date
2166
 * @date2: the second date
2167
 *
2168
 * Checks if @date1 is less than or equal to @date2,
2169
 * and swap the values if this is not the case.
2170
 */
2171
void
2172
g_date_order (GDate *date1,
2173
              GDate *date2)
2174
0
{
2175
0
  g_return_if_fail (g_date_valid (date1));
2176
0
  g_return_if_fail (g_date_valid (date2));
2177
2178
0
  if (g_date_compare (date1, date2) > 0)
2179
0
    {
2180
0
      GDate tmp = *date1;
2181
0
      *date1 = *date2;
2182
0
      *date2 = tmp;
2183
0
    }
2184
0
}
2185
2186
#ifdef G_OS_WIN32
2187
static gboolean
2188
append_month_name (GArray     *result,
2189
       LCID        lcid,
2190
       SYSTEMTIME *systemtime,
2191
       gboolean    abbreviated,
2192
       gboolean    alternative)
2193
{
2194
  int n;
2195
  WORD base;
2196
  LPCWSTR lpFormat;
2197
2198
  if (alternative)
2199
    {
2200
      base = abbreviated ? LOCALE_SABBREVMONTHNAME1 : LOCALE_SMONTHNAME1;
2201
      n = GetLocaleInfoW (lcid, base + systemtime->wMonth - 1, NULL, 0);
2202
      if (n == 0)
2203
        return FALSE;
2204
2205
      g_array_set_size (result, result->len + n);
2206
      if (GetLocaleInfoW (lcid, base + systemtime->wMonth - 1,
2207
                          ((wchar_t *) result->data) + result->len - n, n) != n)
2208
        return FALSE;
2209
2210
      g_array_set_size (result, result->len - 1);
2211
    }
2212
  else
2213
    {
2214
      /* According to MSDN, this is the correct method to obtain
2215
       * the form of the month name used when formatting a full
2216
       * date; it must be a genitive case in some languages.
2217
       *
2218
       * (n == 0) indicates an error, whereas (n < 2) is something we’d never
2219
       * expect from the given format string, and would break the subsequent code.
2220
       */
2221
      lpFormat = abbreviated ? L"ddMMM" : L"ddMMMM";
2222
      n = GetDateFormatW (lcid, 0, systemtime, lpFormat, NULL, 0);
2223
      if (n < 2)
2224
        return FALSE;
2225
2226
      g_array_set_size (result, result->len + n);
2227
      if (GetDateFormatW (lcid, 0, systemtime, lpFormat,
2228
                          ((wchar_t *) result->data) + result->len - n, n) != n)
2229
        return FALSE;
2230
2231
      /* We have obtained a day number as two digits and the month name.
2232
       * Now let's get rid of those two digits: overwrite them with the
2233
       * month name.
2234
       */
2235
      memmove (((wchar_t *) result->data) + result->len - n,
2236
         ((wchar_t *) result->data) + result->len - n + 2,
2237
         (n - 2) * sizeof (wchar_t));
2238
      g_array_set_size (result, result->len - 3);
2239
    }
2240
2241
  return TRUE;
2242
}
2243
2244
static gsize
2245
win32_strftime_helper (const GDate     *d,
2246
           const gchar     *format,
2247
           const struct tm *tm,
2248
           gchar           *s,
2249
           gsize          slen)
2250
{
2251
  SYSTEMTIME systemtime;
2252
  TIME_ZONE_INFORMATION tzinfo;
2253
  LCID lcid;
2254
  int n, k;
2255
  GArray *result;
2256
  const gchar *p;
2257
  gunichar c, modifier;
2258
  const wchar_t digits[] = L"0123456789";
2259
  gchar *convbuf;
2260
  glong convlen = 0;
2261
  gsize retval;
2262
  size_t format_len = strlen (format);
2263
2264
  systemtime.wYear = tm->tm_year + 1900;
2265
  systemtime.wMonth = tm->tm_mon + 1;
2266
  systemtime.wDayOfWeek = tm->tm_wday;
2267
  systemtime.wDay = tm->tm_mday;
2268
  systemtime.wHour = tm->tm_hour;
2269
  systemtime.wMinute = tm->tm_min;
2270
  systemtime.wSecond = tm->tm_sec;
2271
  systemtime.wMilliseconds = 0;
2272
  
2273
  lcid = GetThreadLocale ();
2274
  result = g_array_sized_new (FALSE, FALSE, sizeof (wchar_t),
2275
                              (format_len <= 64) ? (guint) format_len * 2 : 128);
2276
2277
  p = format;
2278
  while (*p)
2279
    {
2280
      c = g_utf8_get_char (p);
2281
      if (c == '%')
2282
  {
2283
    p = g_utf8_next_char (p);
2284
    if (!*p)
2285
      {
2286
        s[0] = '\0';
2287
        g_array_free (result, TRUE);
2288
2289
        return 0;
2290
      }
2291
2292
    modifier = '\0';
2293
    c = g_utf8_get_char (p);
2294
    if (c == 'E' || c == 'O')
2295
      {
2296
        /* "%OB", "%Ob", and "%Oh" are supported, ignore other modified
2297
         * conversion specifiers for now.
2298
         */
2299
        modifier = c;
2300
        p = g_utf8_next_char (p);
2301
        if (!*p)
2302
    {
2303
      s[0] = '\0';
2304
      g_array_free (result, TRUE);
2305
2306
      return 0;
2307
    }
2308
2309
        c = g_utf8_get_char (p);
2310
      }
2311
2312
    switch (c)
2313
      {
2314
      case 'a':
2315
        if (systemtime.wDayOfWeek == 0)
2316
    k = 6;
2317
        else
2318
    k = systemtime.wDayOfWeek - 1;
2319
        n = GetLocaleInfoW (lcid, LOCALE_SABBREVDAYNAME1+k, NULL, 0);
2320
        g_array_set_size (result, result->len + n);
2321
        GetLocaleInfoW (lcid, LOCALE_SABBREVDAYNAME1+k, ((wchar_t *) result->data) + result->len - n, n);
2322
        g_array_set_size (result, result->len - 1);
2323
        break;
2324
      case 'A':
2325
        if (systemtime.wDayOfWeek == 0)
2326
    k = 6;
2327
        else
2328
    k = systemtime.wDayOfWeek - 1;
2329
        n = GetLocaleInfoW (lcid, LOCALE_SDAYNAME1+k, NULL, 0);
2330
        g_array_set_size (result, result->len + n);
2331
        GetLocaleInfoW (lcid, LOCALE_SDAYNAME1+k, ((wchar_t *) result->data) + result->len - n, n);
2332
        g_array_set_size (result, result->len - 1);
2333
        break;
2334
      case 'b':
2335
      case 'h':
2336
              if (!append_month_name (result, lcid, &systemtime, TRUE, modifier == 'O'))
2337
                {
2338
                  /* Ignore the error; this placeholder will be replaced with nothing */
2339
                }
2340
        break;
2341
      case 'B':
2342
              if (!append_month_name (result, lcid, &systemtime, FALSE, modifier == 'O'))
2343
                {
2344
                  /* Ignore the error; this placeholder will be replaced with nothing */
2345
                }
2346
        break;
2347
      case 'c':
2348
        n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
2349
        if (n > 0)
2350
    {
2351
      g_array_set_size (result, result->len + n);
2352
      GetDateFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
2353
      g_array_set_size (result, result->len - 1);
2354
    }
2355
        g_array_append_vals (result, L" ", 1);
2356
        n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
2357
        if (n > 0)
2358
    {
2359
      g_array_set_size (result, result->len + n);
2360
      GetTimeFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
2361
      g_array_set_size (result, result->len - 1);
2362
    }
2363
        break;
2364
      case 'C':
2365
        g_array_append_vals (result, digits + systemtime.wYear/1000, 1);
2366
        g_array_append_vals (result, digits + (systemtime.wYear/1000)%10, 1);
2367
        break;
2368
      case 'd':
2369
        g_array_append_vals (result, digits + systemtime.wDay/10, 1);
2370
        g_array_append_vals (result, digits + systemtime.wDay%10, 1);
2371
        break;
2372
      case 'D':
2373
        g_array_append_vals (result, digits + systemtime.wMonth/10, 1);
2374
        g_array_append_vals (result, digits + systemtime.wMonth%10, 1);
2375
        g_array_append_vals (result, L"/", 1);
2376
        g_array_append_vals (result, digits + systemtime.wDay/10, 1);
2377
        g_array_append_vals (result, digits + systemtime.wDay%10, 1);
2378
        g_array_append_vals (result, L"/", 1);
2379
        g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
2380
        g_array_append_vals (result, digits + systemtime.wYear%10, 1);
2381
        break;
2382
      case 'e':
2383
        if (systemtime.wDay >= 10)
2384
    g_array_append_vals (result, digits + systemtime.wDay/10, 1);
2385
        else
2386
    g_array_append_vals (result, L" ", 1);
2387
        g_array_append_vals (result, digits + systemtime.wDay%10, 1);
2388
        break;
2389
2390
        /* A GDate has no time fields, so for now we can
2391
         * hardcode all time conversions into zeros (or 12 for
2392
         * %I). The alternative code snippets in the #else
2393
         * branches are here ready to be taken into use when
2394
         * needed by a g_strftime() or g_date_and_time_format()
2395
         * or whatever.
2396
         */
2397
      case 'H':
2398
#if 1
2399
        g_array_append_vals (result, L"00", 2);
2400
#else
2401
        g_array_append_vals (result, digits + systemtime.wHour/10, 1);
2402
        g_array_append_vals (result, digits + systemtime.wHour%10, 1);
2403
#endif
2404
        break;
2405
      case 'I':
2406
#if 1
2407
        g_array_append_vals (result, L"12", 2);
2408
#else
2409
        if (systemtime.wHour == 0)
2410
    g_array_append_vals (result, L"12", 2);
2411
        else
2412
    {
2413
      g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
2414
      g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
2415
    }
2416
#endif
2417
        break;
2418
      case  'j':
2419
        g_array_append_vals (result, digits + (tm->tm_yday+1)/100, 1);
2420
        g_array_append_vals (result, digits + ((tm->tm_yday+1)/10)%10, 1);
2421
        g_array_append_vals (result, digits + (tm->tm_yday+1)%10, 1);
2422
        break;
2423
      case 'm':
2424
        g_array_append_vals (result, digits + systemtime.wMonth/10, 1);
2425
        g_array_append_vals (result, digits + systemtime.wMonth%10, 1);
2426
        break;
2427
      case 'M':
2428
#if 1
2429
        g_array_append_vals (result, L"00", 2);
2430
#else
2431
        g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
2432
        g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
2433
#endif
2434
        break;
2435
      case 'n':
2436
        g_array_append_vals (result, L"\n", 1);
2437
        break;
2438
      case 'p':
2439
        n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
2440
        if (n > 0)
2441
    {
2442
      g_array_set_size (result, result->len + n);
2443
      GetTimeFormatW (lcid, 0, &systemtime, L"tt", ((wchar_t *) result->data) + result->len - n, n);
2444
      g_array_set_size (result, result->len - 1);
2445
    }
2446
        break;
2447
      case 'r':
2448
        /* This is a rather odd format. Hard to say what to do.
2449
         * Let's always use the POSIX %I:%M:%S %p
2450
         */
2451
#if 1
2452
        g_array_append_vals (result, L"12:00:00", 8);
2453
#else
2454
        if (systemtime.wHour == 0)
2455
    g_array_append_vals (result, L"12", 2);
2456
        else
2457
    {
2458
      g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
2459
      g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
2460
    }
2461
        g_array_append_vals (result, L":", 1);
2462
        g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
2463
        g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
2464
        g_array_append_vals (result, L":", 1);
2465
        g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
2466
        g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
2467
        g_array_append_vals (result, L" ", 1);
2468
#endif
2469
        n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
2470
        if (n > 0)
2471
    {
2472
      g_array_set_size (result, result->len + n);
2473
      GetTimeFormatW (lcid, 0, &systemtime, L"tt", ((wchar_t *) result->data) + result->len - n, n);
2474
      g_array_set_size (result, result->len - 1);
2475
    }
2476
        break;
2477
      case 'R':
2478
#if 1
2479
        g_array_append_vals (result, L"00:00", 5);
2480
#else
2481
        g_array_append_vals (result, digits + systemtime.wHour/10, 1);
2482
        g_array_append_vals (result, digits + systemtime.wHour%10, 1);
2483
        g_array_append_vals (result, L":", 1);
2484
        g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
2485
        g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
2486
#endif
2487
        break;
2488
      case 'S':
2489
#if 1
2490
        g_array_append_vals (result, L"00", 2);
2491
#else
2492
        g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
2493
        g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
2494
#endif
2495
        break;
2496
      case 't':
2497
        g_array_append_vals (result, L"\t", 1);
2498
        break;
2499
      case 'T':
2500
#if 1
2501
        g_array_append_vals (result, L"00:00:00", 8);
2502
#else
2503
        g_array_append_vals (result, digits + systemtime.wHour/10, 1);
2504
        g_array_append_vals (result, digits + systemtime.wHour%10, 1);
2505
        g_array_append_vals (result, L":", 1);
2506
        g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
2507
        g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
2508
        g_array_append_vals (result, L":", 1);
2509
        g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
2510
        g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
2511
#endif
2512
        break;
2513
      case 'u':
2514
        if (systemtime.wDayOfWeek == 0)
2515
    g_array_append_vals (result, L"7", 1);
2516
        else
2517
    g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
2518
        break;
2519
      case 'U':
2520
        n = g_date_get_sunday_week_of_year (d);
2521
        g_array_append_vals (result, digits + n/10, 1);
2522
        g_array_append_vals (result, digits + n%10, 1);
2523
        break;
2524
      case 'V':
2525
        n = g_date_get_iso8601_week_of_year (d);
2526
        g_array_append_vals (result, digits + n/10, 1);
2527
        g_array_append_vals (result, digits + n%10, 1);
2528
        break;
2529
      case 'w':
2530
        g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
2531
        break;
2532
      case 'W':
2533
        n = g_date_get_monday_week_of_year (d);
2534
        g_array_append_vals (result, digits + n/10, 1);
2535
        g_array_append_vals (result, digits + n%10, 1);
2536
        break;
2537
      case 'x':
2538
        n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
2539
        if (n > 0)
2540
    {
2541
      g_array_set_size (result, result->len + n);
2542
      GetDateFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
2543
      g_array_set_size (result, result->len - 1);
2544
    }
2545
        break;
2546
      case 'X':
2547
        n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
2548
        if (n > 0)
2549
    {
2550
      g_array_set_size (result, result->len + n);
2551
      GetTimeFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
2552
      g_array_set_size (result, result->len - 1);
2553
    }
2554
        break;
2555
      case 'y':
2556
        g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
2557
        g_array_append_vals (result, digits + systemtime.wYear%10, 1);
2558
        break;
2559
      case 'Y':
2560
        g_array_append_vals (result, digits + systemtime.wYear/1000, 1);
2561
        g_array_append_vals (result, digits + (systemtime.wYear/100)%10, 1);
2562
        g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
2563
        g_array_append_vals (result, digits + systemtime.wYear%10, 1);
2564
        break;
2565
      case 'Z':
2566
        n = GetTimeZoneInformation (&tzinfo);
2567
        if (n == TIME_ZONE_ID_UNKNOWN || n == TIME_ZONE_ID_STANDARD)
2568
    g_array_append_vals (result, tzinfo.StandardName, wcslen (tzinfo.StandardName));
2569
        else if (n == TIME_ZONE_ID_DAYLIGHT)
2570
    g_array_append_vals (result, tzinfo.DaylightName, wcslen (tzinfo.DaylightName));
2571
        break;
2572
      case '%':
2573
        g_array_append_vals (result, L"%", 1);
2574
        break;
2575
      }      
2576
  } 
2577
      else if (c <= 0xFFFF)
2578
  {
2579
    wchar_t wc = c;
2580
    g_array_append_vals (result, &wc, 1);
2581
  }
2582
      else
2583
  {
2584
    glong nwc;
2585
    wchar_t *ws;
2586
2587
    ws = g_ucs4_to_utf16 (&c, 1, NULL, &nwc, NULL);
2588
    g_array_append_vals (result, ws, nwc);
2589
    g_free (ws);
2590
  }
2591
      p = g_utf8_next_char (p);
2592
    }
2593
  
2594
  convbuf = g_utf16_to_utf8 ((wchar_t *) result->data, result->len, NULL, &convlen, NULL);
2595
  g_array_free (result, TRUE);
2596
2597
  if (!convbuf)
2598
    {
2599
      s[0] = '\0';
2600
      return 0;
2601
    }
2602
  
2603
  g_assert (convlen >= 0);
2604
  if ((gsize) convlen >= slen)
2605
    {
2606
      /* Ensure only whole characters are copied into the buffer. */
2607
      gchar *end = g_utf8_find_prev_char (convbuf, convbuf + slen);
2608
      g_assert (end != NULL);
2609
      convlen = end - convbuf;
2610
2611
      /* Return 0 because the buffer isn't large enough. */
2612
      retval = 0;
2613
    }
2614
  else
2615
    retval = convlen;
2616
2617
  memcpy (s, convbuf, convlen);
2618
  s[convlen] = '\0';
2619
  g_free (convbuf);
2620
2621
  return retval;
2622
}
2623
2624
#endif
2625
2626
/**
2627
 * g_date_strftime:
2628
 * @s: destination buffer
2629
 * @slen: buffer size
2630
 * @format: format string
2631
 * @date: valid #GDate
2632
 *
2633
 * Generates a printed representation of the date, in a
2634
 * [locale](running.html#locale)-specific way.
2635
 * Works just like the platform's C library strftime() function,
2636
 * but only accepts date-related formats; time-related formats
2637
 * give undefined results. Date must be valid. Unlike strftime()
2638
 * (which uses the locale encoding), works on a UTF-8 format
2639
 * string and stores a UTF-8 result.
2640
 *
2641
 * This function does not provide any conversion specifiers in
2642
 * addition to those implemented by the platform's C library.
2643
 * For example, don't expect that using g_date_strftime() would
2644
 * make the \%F provided by the C99 strftime() work on Windows
2645
 * where the C library only complies to C89.
2646
 *
2647
 * Returns: number of characters written to the buffer, or `0` if the buffer was too small
2648
 */
2649
#pragma GCC diagnostic push
2650
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
2651
2652
gsize     
2653
g_date_strftime (gchar       *s, 
2654
                 gsize        slen, 
2655
                 const gchar *format, 
2656
                 const GDate *d)
2657
0
{
2658
0
  struct tm tm;
2659
0
#ifndef G_OS_WIN32
2660
0
  gsize locale_format_len = 0;
2661
0
  gchar *locale_format;
2662
0
  gsize tmplen;
2663
0
  gchar *tmpbuf;
2664
0
  gsize tmpbufsize;
2665
0
  gsize convlen = 0;
2666
0
  gchar *convbuf;
2667
0
  GError *error = NULL;
2668
0
  gsize retval;
2669
0
#endif
2670
2671
0
  g_return_val_if_fail (g_date_valid (d), 0);
2672
0
  g_return_val_if_fail (slen > 0, 0); 
2673
0
  g_return_val_if_fail (format != NULL, 0);
2674
0
  g_return_val_if_fail (s != NULL, 0);
2675
2676
0
  g_date_to_struct_tm (d, &tm);
2677
2678
#ifdef G_OS_WIN32
2679
  if (!g_utf8_validate (format, -1, NULL))
2680
    {
2681
      s[0] = '\0';
2682
      return 0;
2683
    }
2684
  return win32_strftime_helper (d, format, &tm, s, slen);
2685
#else
2686
2687
0
  locale_format = g_locale_from_utf8 (format, -1, NULL, &locale_format_len, &error);
2688
2689
0
  if (error)
2690
0
    {
2691
0
      g_warning (G_STRLOC "Error converting format to locale encoding: %s", error->message);
2692
0
      g_error_free (error);
2693
2694
0
      s[0] = '\0';
2695
0
      return 0;
2696
0
    }
2697
2698
0
  tmpbufsize = MAX (128, locale_format_len * 2);
2699
0
  while (TRUE)
2700
0
    {
2701
0
      tmpbuf = g_malloc (tmpbufsize);
2702
2703
      /* Set the first byte to something other than '\0', to be able to
2704
       * recognize whether strftime actually failed or just returned "".
2705
       */
2706
0
      tmpbuf[0] = '\1';
2707
0
      tmplen = strftime (tmpbuf, tmpbufsize, locale_format, &tm);
2708
2709
0
      if (tmplen == 0 && tmpbuf[0] != '\0')
2710
0
        {
2711
0
          g_free (tmpbuf);
2712
0
          tmpbufsize *= 2;
2713
2714
0
          if (tmpbufsize > 65536)
2715
0
            {
2716
0
              g_warning (G_STRLOC "Maximum buffer size for g_date_strftime exceeded: giving up");
2717
0
              g_free (locale_format);
2718
2719
0
              s[0] = '\0';
2720
0
              return 0;
2721
0
            }
2722
0
        }
2723
0
      else
2724
0
        break;
2725
0
    }
2726
0
  g_free (locale_format);
2727
2728
0
  convbuf = g_locale_to_utf8 (tmpbuf, tmplen, NULL, &convlen, &error);
2729
0
  g_free (tmpbuf);
2730
2731
0
  if (error)
2732
0
    {
2733
0
      g_warning (G_STRLOC "Error converting results of strftime to UTF-8: %s", error->message);
2734
0
      g_error_free (error);
2735
2736
0
      g_assert (convbuf == NULL);
2737
2738
0
      s[0] = '\0';
2739
0
      return 0;
2740
0
    }
2741
2742
0
  if (slen <= convlen)
2743
0
    {
2744
      /* Ensure only whole characters are copied into the buffer.
2745
       */
2746
0
      gchar *end = g_utf8_find_prev_char (convbuf, convbuf + slen);
2747
0
      g_assert (end != NULL);
2748
0
      convlen = end - convbuf;
2749
2750
      /* Return 0 because the buffer isn't large enough.
2751
       */
2752
0
      retval = 0;
2753
0
    }
2754
0
  else
2755
0
    retval = convlen;
2756
2757
0
  memcpy (s, convbuf, convlen);
2758
0
  s[convlen] = '\0';
2759
0
  g_free (convbuf);
2760
2761
0
  return retval;
2762
0
#endif
2763
0
}
2764
2765
#pragma GCC diagnostic pop