#warning isn't portable, check for gcc
[platform/upstream/glib.git] / glib / gdate.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /* 
21  * MT safe
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include "glib.h"
29
30 #include <time.h>
31 #include <string.h>
32 #include <ctype.h>
33 #include <stdlib.h>
34 #include <locale.h>
35
36 GDate*
37 g_date_new ()
38 {
39   GDate *d = g_new0 (GDate, 1); /* happily, 0 is the invalid flag for everything. */
40   
41   return d;
42 }
43
44 GDate*
45 g_date_new_dmy (GDateDay day, GDateMonth m, GDateYear y)
46 {
47   GDate *d;
48   g_return_val_if_fail (g_date_valid_dmy (day, m, y), NULL);
49   
50   d = g_new (GDate, 1);
51   
52   d->julian = FALSE;
53   d->dmy    = TRUE;
54   
55   d->month = m;
56   d->day   = day;
57   d->year  = y;
58   
59   g_assert (g_date_valid (d));
60   
61   return d;
62 }
63
64 GDate*
65 g_date_new_julian (guint32 j)
66 {
67   GDate *d;
68   g_return_val_if_fail (g_date_valid_julian (j), NULL);
69   
70   d = g_new (GDate, 1);
71   
72   d->julian = TRUE;
73   d->dmy    = FALSE;
74   
75   d->julian_days = j;
76   
77   g_assert (g_date_valid (d));
78   
79   return d;
80 }
81
82 void
83 g_date_free (GDate *d)
84 {
85   g_return_if_fail (d != NULL);
86   
87   g_free (d);
88 }
89
90 gboolean     
91 g_date_valid (GDate       *d)
92 {
93   g_return_val_if_fail (d != NULL, FALSE);
94   
95   return (d->julian || d->dmy);
96 }
97
98 static const guint8 days_in_months[2][13] = 
99 {  /* error, jan feb mar apr may jun jul aug sep oct nov dec */
100   {  0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, 
101   {  0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } /* leap year */
102 };
103
104 static const guint16 days_in_year[2][14] = 
105 {  /* 0, jan feb mar apr may  jun  jul  aug  sep  oct  nov  dec */
106   {  0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, 
107   {  0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
108 };
109
110 gboolean     
111 g_date_valid_month (GDateMonth   m)
112
113   return ( (m > G_DATE_BAD_MONTH) && (m < 13) );
114 }
115
116 gboolean     
117 g_date_valid_year (GDateYear    y)
118 {
119   return ( y > G_DATE_BAD_YEAR );
120 }
121
122 gboolean     
123 g_date_valid_day (GDateDay     d)
124 {
125   return ( (d > G_DATE_BAD_DAY) && (d < 32) );
126 }
127
128 gboolean     
129 g_date_valid_weekday (GDateWeekday w)
130 {
131   return ( (w > G_DATE_BAD_WEEKDAY) && (w < 8) );
132 }
133
134 gboolean     
135 g_date_valid_julian (guint32      j)
136 {
137   return (j > G_DATE_BAD_JULIAN);
138 }
139
140 gboolean     
141 g_date_valid_dmy (GDateDay     d, 
142                   GDateMonth   m, 
143                   GDateYear    y)
144 {
145   return ( (m > G_DATE_BAD_MONTH) &&
146            (m < 13)               && 
147            (d > G_DATE_BAD_DAY)   && 
148            (y > G_DATE_BAD_YEAR)  &&   /* must check before using g_date_is_leap_year */
149            (d <=  (g_date_is_leap_year (y) ? 
150                    days_in_months[1][m] : days_in_months[0][m])) );
151 }
152
153
154 /* "Julian days" just means an absolute number of days, where Day 1 ==
155  *   Jan 1, Year 1
156  */
157 static void
158 g_date_update_julian (GDate *d)
159 {
160   GDateYear year;
161   gint index;
162   
163   g_return_if_fail (d != NULL);
164   g_return_if_fail (d->dmy);
165   g_return_if_fail (!d->julian);
166   g_return_if_fail (g_date_valid_dmy (d->day, d->month, d->year));
167   
168   /* What we actually do is: multiply years * 365 days in the year,
169    *  add the number of years divided by 4, subtract the number of
170    *  years divided by 100 and add the number of years divided by 400,
171    *  which accounts for leap year stuff. Code from Steffen Beyer's
172    *  DateCalc. 
173    */
174   
175   year = d->year - 1; /* we know d->year > 0 since it's valid */
176   
177   d->julian_days = year * 365U;
178   d->julian_days += (year >>= 2); /* divide by 4 and add */
179   d->julian_days -= (year /= 25); /* divides original # years by 100 */
180   d->julian_days += year >> 2;    /* divides by 4, which divides original by 400 */
181   
182   index = g_date_is_leap_year (d->year) ? 1 : 0;
183   
184   d->julian_days += days_in_year[index][d->month] + d->day;
185   
186   g_return_if_fail (g_date_valid_julian (d->julian_days));
187   
188   d->julian = TRUE;
189 }
190
191 static void 
192 g_date_update_dmy (GDate *d)
193 {
194   GDateYear y;
195   GDateMonth m;
196   GDateDay day;
197   
198   guint32 A, B, C, D, E, M;
199   
200   g_return_if_fail (d != NULL);
201   g_return_if_fail (d->julian);
202   g_return_if_fail (!d->dmy);
203   g_return_if_fail (g_date_valid_julian (d->julian_days));
204   
205   /* Formula taken from the Calendar FAQ; the formula was for the
206    *  Julian Period which starts on 1 January 4713 BC, so we add
207    *  1,721,425 to the number of days before doing the formula.
208    *
209    * I'm sure this can be simplified for our 1 January 1 AD period
210    * start, but I can't figure out how to unpack the formula.  
211    */
212   
213   A = d->julian_days + 1721425 + 32045;
214   B = ( 4 *(A + 36524) )/ 146097 - 1;
215   C = A - (146097 * B)/4;
216   D = ( 4 * (C + 365) ) / 1461 - 1;
217   E = C - ((1461*D) / 4);
218   M = (5 * (E - 1) + 2)/153;
219   
220   m = M + 3 - (12*(M/10));
221   day = E - (153*M + 2)/5;
222   y = 100 * B + D - 4800 + (M/10);
223   
224 #ifdef G_ENABLE_DEBUG
225   if (!g_date_valid_dmy (day, m, y)) 
226     {
227       g_warning ("\nOOPS julian: %u  computed dmy: %u %u %u\n", 
228                  d->julian_days, day, m, y);
229     }
230 #endif
231   
232   d->month = m;
233   d->day   = day;
234   d->year  = y;
235   
236   d->dmy = TRUE;
237 }
238
239 GDateWeekday 
240 g_date_weekday (GDate *d)
241 {
242   g_return_val_if_fail (d != NULL, G_DATE_BAD_WEEKDAY);
243   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_WEEKDAY);
244   
245   if (!d->julian) 
246     {
247       g_date_update_julian (d);
248     }
249   g_return_val_if_fail (d->julian, G_DATE_BAD_WEEKDAY);
250   
251   return ((d->julian_days - 1) % 7) + 1;
252 }
253
254 GDateMonth   
255 g_date_month (GDate *d)
256 {
257   g_return_val_if_fail (d != NULL, G_DATE_BAD_MONTH);
258   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_MONTH);
259   
260   if (!d->dmy) 
261     {
262       g_date_update_dmy (d);
263     }
264   g_return_val_if_fail (d->dmy, G_DATE_BAD_MONTH);
265   
266   return d->month;
267 }
268
269 GDateYear    
270 g_date_year (GDate *d)
271 {
272   g_return_val_if_fail (d != NULL, G_DATE_BAD_YEAR);
273   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_YEAR);
274   
275   if (!d->dmy) 
276     {
277       g_date_update_dmy (d);
278     }
279   g_return_val_if_fail (d->dmy, G_DATE_BAD_YEAR);  
280   
281   return d->year;
282 }
283
284 GDateDay     
285 g_date_day (GDate *d)
286 {
287   g_return_val_if_fail (d != NULL, G_DATE_BAD_DAY);
288   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_DAY);
289   
290   if (!d->dmy) 
291     {
292       g_date_update_dmy (d);
293     }
294   g_return_val_if_fail (d->dmy, G_DATE_BAD_DAY);  
295   
296   return d->day;
297 }
298
299 guint32      
300 g_date_julian (GDate *d)
301 {
302   g_return_val_if_fail (d != NULL, G_DATE_BAD_JULIAN);
303   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_JULIAN);
304   
305   if (!d->julian) 
306     {
307       g_date_update_julian (d);
308     }
309   g_return_val_if_fail (d->julian, G_DATE_BAD_JULIAN);  
310   
311   return d->julian_days;
312 }
313
314 guint        
315 g_date_day_of_year (GDate *d)
316 {
317   gint index;
318   
319   g_return_val_if_fail (d != NULL, 0);
320   g_return_val_if_fail (g_date_valid (d), 0);
321   
322   if (!d->dmy) 
323     {
324       g_date_update_dmy (d);
325     }
326   g_return_val_if_fail (d->dmy, 0);  
327   
328   index = g_date_is_leap_year (d->year) ? 1 : 0;
329   
330   return (days_in_year[index][d->month] + d->day);
331 }
332
333 guint        
334 g_date_monday_week_of_year (GDate *d)
335 {
336   GDateWeekday wd;
337   guint day;
338   GDate first;
339   
340   g_return_val_if_fail (d != NULL, 0);
341   g_return_val_if_fail (g_date_valid (d), 0);
342   
343   if (!d->dmy) 
344     {
345       g_date_update_dmy (d);
346     }
347   g_return_val_if_fail (d->dmy, 0);  
348   
349   g_date_clear (&first, 1);
350   
351   g_date_set_dmy (&first, 1, 1, d->year);
352   
353   wd = g_date_weekday (&first) - 1; /* make Monday day 0 */
354   day = g_date_day_of_year (d) - 1;
355   
356   return ((day + wd)/7U + (wd == 0 ? 1 : 0));
357 }
358
359 guint        
360 g_date_sunday_week_of_year (GDate *d)
361 {
362   GDateWeekday wd;
363   guint day;
364   GDate first;
365   
366   g_return_val_if_fail (d != NULL, 0);
367   g_return_val_if_fail (g_date_valid (d), 0);
368   
369   if (!d->dmy) 
370     {
371       g_date_update_dmy (d);
372     }
373   g_return_val_if_fail (d->dmy, 0);  
374   
375   g_date_clear (&first, 1);
376   
377   g_date_set_dmy (&first, 1, 1, d->year);
378   
379   wd = g_date_weekday (&first);
380   if (wd == 7) wd = 0; /* make Sunday day 0 */
381   day = g_date_day_of_year (d) - 1;
382   
383   return ((day + wd)/7U + (wd == 0 ? 1 : 0));
384 }
385
386 void         
387 g_date_clear (GDate       *d, guint ndates)
388 {
389   g_return_if_fail (d != NULL);
390   g_return_if_fail (ndates != 0);
391   
392   memset (d, 0x0, ndates*sizeof (GDate)); 
393 }
394
395 G_LOCK_DECLARE_STATIC (g_date_global);
396
397 /* These are for the parser, output to the user should use *
398  * g_date_strftime () - this creates more never-freed memory to annoy
399  * all those memory debugger users. :-) 
400  */
401
402 static gchar *long_month_names[13] = 
403
404   "Error", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL 
405 };
406
407 static gchar *short_month_names[13] = 
408 {
409   "Error", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL 
410 };
411
412 /* This tells us if we need to update the parse info */
413 static gchar *current_locale = NULL;
414
415 /* order of these in the current locale */
416 static GDateDMY dmy_order[3] = 
417 {
418    G_DATE_DAY, G_DATE_MONTH, G_DATE_YEAR
419 };
420
421 /* Where to chop two-digit years: i.e., for the 1930 default, numbers
422  * 29 and below are counted as in the year 2000, numbers 30 and above
423  * are counted as in the year 1900.  
424  */
425
426 static GDateYear twodigit_start_year = 1930;
427
428 /* It is impossible to enter a year between 1 AD and 99 AD with this
429  * in effect.  
430  */
431 static gboolean using_twodigit_years = FALSE;
432
433 struct _GDateParseTokens {
434   gint num_ints;
435   gint n[3];
436   guint month;
437 };
438
439 typedef struct _GDateParseTokens GDateParseTokens;
440
441 #define NUM_LEN 10
442
443 /* HOLDS: g_date_global_lock */
444 static void
445 g_date_fill_parse_tokens (const gchar *str, GDateParseTokens *pt)
446 {
447   gchar num[4][NUM_LEN+1];
448   gint i;
449   const gchar *s;
450   
451   /* We count 4, but store 3; so we can give an error
452    * if there are 4.
453    */
454   num[0][0] = num[1][0] = num[2][0] = num[3][0] = '\0';
455   
456   s = str;
457   pt->num_ints = 0;
458   while (*s && pt->num_ints < 4) 
459     {
460       
461       i = 0;
462       while (*s && isdigit (*s) && i <= NUM_LEN)
463         {
464           num[pt->num_ints][i] = *s;
465           ++s; 
466           ++i;
467         }
468       
469       if (i > 0) 
470         {
471           num[pt->num_ints][i] = '\0';
472           ++(pt->num_ints);
473         }
474       
475       if (*s == '\0') break;
476       
477       ++s;
478     }
479   
480   pt->n[0] = pt->num_ints > 0 ? atoi (num[0]) : 0;
481   pt->n[1] = pt->num_ints > 1 ? atoi (num[1]) : 0;
482   pt->n[2] = pt->num_ints > 2 ? atoi (num[2]) : 0;
483   
484   pt->month = G_DATE_BAD_MONTH;
485   
486   if (pt->num_ints < 3)
487     {
488       gchar lcstr[128];
489       int i = 1;
490       
491       strncpy (lcstr, str, 127);
492       g_strdown (lcstr);
493       
494       while (i < 13)
495         {
496           if (long_month_names[i] != NULL) 
497             {
498               const gchar *found = strstr (lcstr, long_month_names[i]);
499               
500               if (found != NULL)
501                 {
502                   pt->month = i;
503                   return;
504                 }
505             }
506           
507           if (short_month_names[i] != NULL) 
508             {
509               const gchar *found = strstr (lcstr, short_month_names[i]);
510               
511               if (found != NULL)
512                 {
513                   pt->month = i;
514                   return;
515                 }
516             }
517
518           ++i;
519         }      
520     }
521 }
522
523 /* HOLDS: g_date_global_lock */
524 static void
525 g_date_prepare_to_parse (const gchar *str, GDateParseTokens *pt)
526 {
527   const gchar *locale = setlocale (LC_TIME, NULL);
528   gboolean recompute_localeinfo = FALSE;
529   GDate d;
530   
531   g_return_if_fail (locale != NULL); /* should not happen */
532   
533   g_date_clear (&d, 1);              /* clear for scratch use */
534   
535   if ( (current_locale == NULL) || (strcmp (locale, current_locale) != 0) ) 
536     {
537       recompute_localeinfo = TRUE;  /* Uh, there used to be a reason for the temporary */
538     }
539   
540   if (recompute_localeinfo)
541     {
542       int i = 1;
543       GDateParseTokens testpt;
544       gchar buf[128];
545       
546       g_free (current_locale); /* still works if current_locale == NULL */
547       
548       current_locale = g_strdup (locale);
549       
550       while (i < 13) 
551         {
552           g_date_set_dmy (&d, 1, i, 1);
553           
554           g_return_if_fail (g_date_valid (&d));
555           
556           g_date_strftime (buf, 127, "%b", &d);
557           g_free (short_month_names[i]);
558           g_strdown (buf);
559           short_month_names[i] = g_strdup (buf);
560           
561           
562           
563           g_date_strftime (buf, 127, "%B", &d);
564           g_free (long_month_names[i]);
565           g_strdown (buf);
566           long_month_names[i] = g_strdup (buf);
567           
568           ++i;
569         }
570       
571       /* Determine DMY order */
572       
573       /* had to pick a random day - don't change this, some strftimes
574        * are broken on some days, and this one is good so far. */
575       g_date_set_dmy (&d, 4, 7, 1976);
576       
577       g_date_strftime (buf, 127, "%x", &d);
578       
579       g_date_fill_parse_tokens (buf, &testpt);
580       
581       i = 0;
582       while (i < testpt.num_ints)
583         {
584           switch (testpt.n[i])
585             {
586             case 7:
587               dmy_order[i] = G_DATE_MONTH;
588               break;
589             case 4:
590               dmy_order[i] = G_DATE_DAY;
591               break;
592             case 76:
593               using_twodigit_years = TRUE; /* FALL THRU */
594             case 1976:
595               dmy_order[i] = G_DATE_YEAR;
596               break;
597             default:
598               /* leave it unchanged */
599               break;
600             }
601           ++i;
602         }
603       
604 #ifdef G_ENABLE_DEBUG
605       g_message ("**GDate prepared a new set of locale-specific parse rules.");
606       i = 1;
607       while (i < 13) 
608         {
609           g_message ("  %s   %s", long_month_names[i], short_month_names[i]);
610           ++i;
611         }
612       if (using_twodigit_years)
613         {
614           g_message ("**Using twodigit years with cutoff year: %u", twodigit_start_year);
615         }
616       { 
617         gchar *strings[3];
618         i = 0;
619         while (i < 3)
620           {
621             switch (dmy_order[i])
622               {
623               case G_DATE_MONTH:
624                 strings[i] = "Month";
625                 break;
626               case G_DATE_YEAR:
627                 strings[i] = "Year";
628                 break;
629               case G_DATE_DAY:
630                 strings[i] = "Day";
631                 break;
632               default:
633                 strings[i] = NULL;
634                 break;
635               }
636             ++i;
637           }
638         g_message ("**Order: %s, %s, %s", strings[0], strings[1], strings[2]);
639         g_message ("**Sample date in this locale: `%s'", buf);
640       }
641 #endif
642     }
643   
644   g_date_fill_parse_tokens (str, pt);
645 }
646
647 void         
648 g_date_set_parse (GDate       *d, 
649                   const gchar *str)
650 {
651   GDateParseTokens pt;
652   guint m = G_DATE_BAD_MONTH, day = G_DATE_BAD_DAY, y = G_DATE_BAD_YEAR;
653   
654   g_return_if_fail (d != NULL);
655   
656   /* set invalid */
657   g_date_clear (d, 1);
658   
659   G_LOCK (g_date_global);
660
661   g_date_prepare_to_parse (str, &pt);
662   
663 #ifdef G_ENABLE_DEBUG
664   g_message ("Found %d ints, `%d' `%d' `%d' and written out month %d", 
665              pt.num_ints, pt.n[0], pt.n[1], pt.n[2], pt.month);
666 #endif
667   
668   
669   if (pt.num_ints == 4) 
670     {
671       G_UNLOCK (g_date_global);
672       return; /* presumably a typo; bail out. */
673     }
674   
675   if (pt.num_ints > 1)
676     {
677       int i = 0;
678       int j = 0;
679       
680       g_assert (pt.num_ints < 4); /* i.e., it is 2 or 3 */
681       
682       while (i < pt.num_ints && j < 3) 
683         {
684           switch (dmy_order[j])
685             {
686             case G_DATE_MONTH:
687             {
688               if (pt.num_ints == 2 && pt.month != G_DATE_BAD_MONTH)
689                 {
690                   m = pt.month;
691                   ++j;      /* skip months, but don't skip this number */
692                   continue;
693                 }
694               else 
695                 m = pt.n[i];
696             }
697             break;
698             case G_DATE_DAY:
699             {
700               if (pt.num_ints == 2 && pt.month == G_DATE_BAD_MONTH)
701                 {
702                   day = 1;
703                   ++j;      /* skip days, since we may have month/year */
704                   continue;
705                 }
706               day = pt.n[i];
707             }
708             break;
709             case G_DATE_YEAR:
710             {
711               y  = pt.n[i];
712               
713               if (using_twodigit_years && y < 100)
714                 {
715                   guint two     =  twodigit_start_year % 100;
716                   guint century = (twodigit_start_year / 100) * 100;
717                   
718                   if (y < two)
719                     century += 100;
720                   
721                   y += century;
722                 }
723             }
724             break;
725             default:
726               break;
727             }
728           
729           ++i;
730           ++j;
731         }
732       
733       
734       if (pt.num_ints == 3 && !g_date_valid_dmy (day, m, y))
735         {
736           /* Try YYYY MM DD */
737           y   = pt.n[0];
738           m   = pt.n[1];
739           day = pt.n[2];
740           
741           if (using_twodigit_years && y < 100) 
742             y = G_DATE_BAD_YEAR; /* avoids ambiguity */
743         }
744     }
745   else if (pt.num_ints == 1) 
746     {
747       if (pt.month != G_DATE_BAD_MONTH)
748         {
749           /* Month name and year? */
750           m    = pt.month;
751           day  = 1;
752           y = pt.n[0];
753         }
754       else
755         {
756           /* Try yyyymmdd and yymmdd */
757           
758           m   = (pt.n[0]/100) % 100;
759           day = pt.n[0] % 100;
760           y   = pt.n[0]/10000;
761           
762           /* FIXME move this into a separate function */
763           if (using_twodigit_years && y < 100)
764             {
765               guint two     =  twodigit_start_year % 100;
766               guint century = (twodigit_start_year / 100) * 100;
767               
768               if (y < two)
769                 century += 100;
770               
771               y += century;
772             }
773         }
774     }
775   
776   /* See if we got anything valid out of all this. */
777   /* y < 8000 is to catch 19998 style typos; the library is OK up to 65535 or so */
778   if (y < 8000 && g_date_valid_dmy (day, m, y)) 
779     {
780       d->month = m;
781       d->day   = day;
782       d->year  = y;
783       d->dmy   = TRUE;
784     }
785 #ifdef G_ENABLE_DEBUG
786   else 
787     g_message ("Rejected DMY %u %u %u", day, m, y);
788 #endif
789   G_UNLOCK (g_date_global);
790 }
791
792 void         
793 g_date_set_time (GDate *d,
794                  GTime  time)
795 {
796   time_t t = time;
797   struct tm tm;
798   
799   g_return_if_fail (d != NULL);
800   
801 #ifdef HAVE_LOCALTIME_R
802   localtime_r (&t, &tm);
803 #else
804 #  if defined(G_THREADS_ENABLED) && defined(__GNUC__)
805 #  warning "the `g_date_set_time' function will not be MT-safe"
806 #  warning "because there is no `localtime_r' on your system."
807 #  endif
808   {
809     struct tm *ptm = localtime (&t);
810     g_assert (ptm);
811     memcpy ((void *) &tm, (void *) ptm, sizeof(struct tm));
812   }
813 #endif
814   
815   d->julian = FALSE;
816   
817   d->month = tm.tm_mon + 1;
818   d->day   = tm.tm_mday;
819   d->year  = tm.tm_year + 1900;
820   
821   g_return_if_fail (g_date_valid_dmy (d->day, d->month, d->year));
822   
823   d->dmy    = TRUE;
824 }
825
826 void         
827 g_date_set_month (GDate     *d, 
828                   GDateMonth m)
829 {
830   g_return_if_fail (d != NULL);
831   g_return_if_fail (g_date_valid_month (m));
832
833   if (d->julian && !d->dmy) g_date_update_dmy(d);
834   d->julian = FALSE;
835   
836   d->month = m;
837   
838   if (g_date_valid_dmy (d->day, d->month, d->year))
839     d->dmy = TRUE;
840   else 
841     d->dmy = FALSE;
842 }
843
844 void         
845 g_date_set_day (GDate     *d, 
846                 GDateDay day)
847 {
848   g_return_if_fail (d != NULL);
849   g_return_if_fail (g_date_valid_day (day));
850   
851   if (d->julian && !d->dmy) g_date_update_dmy(d);
852   d->julian = FALSE;
853   
854   d->day = day;
855   
856   if (g_date_valid_dmy (d->day, d->month, d->year))
857     d->dmy = TRUE;
858   else 
859     d->dmy = FALSE;
860 }
861
862 void         
863 g_date_set_year (GDate     *d, 
864                  GDateYear  y)
865 {
866   g_return_if_fail (d != NULL);
867   g_return_if_fail (g_date_valid_year (y));
868   
869   if (d->julian && !d->dmy) g_date_update_dmy(d);
870   d->julian = FALSE;
871   
872   d->year = y;
873   
874   if (g_date_valid_dmy (d->day, d->month, d->year))
875     d->dmy = TRUE;
876   else 
877     d->dmy = FALSE;
878 }
879
880 void         
881 g_date_set_dmy (GDate     *d, 
882                 GDateDay   day, 
883                 GDateMonth m, 
884                 GDateYear  y)
885 {
886   g_return_if_fail (d != NULL);
887   g_return_if_fail (g_date_valid_dmy (day, m, y));
888   
889   d->julian = FALSE;
890   
891   d->month = m;
892   d->day   = day;
893   d->year  = y;
894   
895   d->dmy = TRUE;
896 }
897
898 void         
899 g_date_set_julian (GDate *d, guint32 j)
900 {
901   g_return_if_fail (d != NULL);
902   g_return_if_fail (g_date_valid_julian (j));
903   
904   d->julian_days = j;
905   d->julian = TRUE;
906   d->dmy = FALSE;
907 }
908
909
910 gboolean     
911 g_date_is_first_of_month (GDate *d)
912 {
913   g_return_val_if_fail (d != NULL, FALSE);
914   g_return_val_if_fail (g_date_valid (d), FALSE);
915   
916   if (!d->dmy) 
917     {
918       g_date_update_dmy (d);
919     }
920   g_return_val_if_fail (d->dmy, FALSE);  
921   
922   if (d->day == 1) return TRUE;
923   else return FALSE;
924 }
925
926 gboolean     
927 g_date_is_last_of_month (GDate *d)
928 {
929   gint index;
930   
931   g_return_val_if_fail (d != NULL, FALSE);
932   g_return_val_if_fail (g_date_valid (d), FALSE);
933   
934   if (!d->dmy) 
935     {
936       g_date_update_dmy (d);
937     }
938   g_return_val_if_fail (d->dmy, FALSE);  
939   
940   index = g_date_is_leap_year (d->year) ? 1 : 0;
941   
942   if (d->day == days_in_months[index][d->month]) return TRUE;
943   else return FALSE;
944 }
945
946 void         
947 g_date_add_days (GDate *d, guint ndays)
948 {
949   g_return_if_fail (d != NULL);
950   g_return_if_fail (g_date_valid (d));
951   
952   if (!d->julian)
953     {
954       g_date_update_julian (d);
955     }
956   g_return_if_fail (d->julian);
957   
958   d->julian_days += ndays;
959   d->dmy = FALSE;
960 }
961
962 void         
963 g_date_subtract_days (GDate *d, guint ndays)
964 {
965   g_return_if_fail (d != NULL);
966   g_return_if_fail (g_date_valid (d));
967   
968   if (!d->julian)
969     {
970       g_date_update_julian (d);
971     }
972   g_return_if_fail (d->julian);
973   g_return_if_fail (d->julian_days > ndays);
974   
975   d->julian_days -= ndays;
976   d->dmy = FALSE;
977 }
978
979 void         
980 g_date_add_months (GDate       *d, 
981                    guint        nmonths)
982 {
983   guint years, months;
984   gint index;
985   
986   g_return_if_fail (d != NULL);
987   g_return_if_fail (g_date_valid (d));
988   
989   if (!d->dmy) 
990     {
991       g_date_update_dmy (d);
992     }
993   g_return_if_fail (d->dmy);  
994   
995   nmonths += d->month - 1;
996   
997   years  = nmonths/12;
998   months = nmonths%12;
999   
1000   d->month = months + 1;
1001   d->year  += years;
1002   
1003   index = g_date_is_leap_year (d->year) ? 1 : 0;
1004   
1005   if (d->day > days_in_months[index][d->month])
1006     d->day = days_in_months[index][d->month];
1007   
1008   d->julian = FALSE;
1009   
1010   g_return_if_fail (g_date_valid (d));
1011 }
1012
1013 void         
1014 g_date_subtract_months (GDate       *d, 
1015                         guint        nmonths)
1016 {
1017   guint years, months;
1018   gint index;
1019   
1020   g_return_if_fail (d != NULL);
1021   g_return_if_fail (g_date_valid (d));
1022   
1023   if (!d->dmy) 
1024     {
1025       g_date_update_dmy (d);
1026     }
1027   g_return_if_fail (d->dmy);  
1028   
1029   years  = nmonths/12;
1030   months = nmonths%12;
1031   
1032   g_return_if_fail (d->year > years);
1033   
1034   d->year  -= years;
1035   
1036   if (d->month > months) d->month -= months;
1037   else 
1038     {
1039       months -= d->month;
1040       d->month = 12 - months;
1041       d->year -= 1;
1042     }
1043   
1044   index = g_date_is_leap_year (d->year) ? 1 : 0;
1045   
1046   if (d->day > days_in_months[index][d->month])
1047     d->day = days_in_months[index][d->month];
1048   
1049   d->julian = FALSE;
1050   
1051   g_return_if_fail (g_date_valid (d));
1052 }
1053
1054 void         
1055 g_date_add_years (GDate       *d, 
1056                   guint        nyears)
1057 {
1058   g_return_if_fail (d != NULL);
1059   g_return_if_fail (g_date_valid (d));
1060   
1061   if (!d->dmy) 
1062     {
1063       g_date_update_dmy (d);
1064     }
1065   g_return_if_fail (d->dmy);  
1066   
1067   d->year += nyears;
1068   
1069   if (d->month == 2 && d->day == 29)
1070     {
1071       if (!g_date_is_leap_year (d->year))
1072         {
1073           d->day = 28;
1074         }
1075     }
1076   
1077   d->julian = FALSE;
1078 }
1079
1080 void         
1081 g_date_subtract_years (GDate       *d, 
1082                        guint        nyears)
1083 {
1084   g_return_if_fail (d != NULL);
1085   g_return_if_fail (g_date_valid (d));
1086   
1087   if (!d->dmy) 
1088     {
1089       g_date_update_dmy (d);
1090     }
1091   g_return_if_fail (d->dmy);  
1092   g_return_if_fail (d->year > nyears);
1093   
1094   d->year -= nyears;
1095   
1096   if (d->month == 2 && d->day == 29)
1097     {
1098       if (!g_date_is_leap_year (d->year))
1099         {
1100           d->day = 28;
1101         }
1102     }
1103   
1104   d->julian = FALSE;
1105 }
1106
1107
1108 gboolean     
1109 g_date_is_leap_year (GDateYear  year)
1110 {
1111   g_return_val_if_fail (g_date_valid_year (year), FALSE);
1112   
1113   return ( (((year % 4) == 0) && ((year % 100) != 0)) ||
1114            (year % 400) == 0 );
1115 }
1116
1117 guint8         
1118 g_date_days_in_month (GDateMonth month, 
1119                       GDateYear  year)
1120 {
1121   gint index;
1122   
1123   g_return_val_if_fail (g_date_valid_year (year), 0);
1124   g_return_val_if_fail (g_date_valid_month (month), 0);
1125   
1126   index = g_date_is_leap_year (year) ? 1 : 0;
1127   
1128   return days_in_months[index][month];
1129 }
1130
1131 guint8       
1132 g_date_monday_weeks_in_year (GDateYear  year)
1133 {
1134   GDate d;
1135   
1136   g_return_val_if_fail (g_date_valid_year (year), 0);
1137   
1138   g_date_clear (&d, 1);
1139   g_date_set_dmy (&d, 1, 1, year);
1140   if (g_date_weekday (&d) == G_DATE_MONDAY) return 53;
1141   g_date_set_dmy (&d, 31, 12, year);
1142   if (g_date_weekday (&d) == G_DATE_MONDAY) return 53;
1143   if (g_date_is_leap_year (year)) 
1144     {
1145       g_date_set_dmy (&d, 2, 1, year);
1146       if (g_date_weekday (&d) == G_DATE_MONDAY) return 53;
1147       g_date_set_dmy (&d, 30, 12, year);
1148       if (g_date_weekday (&d) == G_DATE_MONDAY) return 53;
1149     }
1150   return 52;
1151 }
1152
1153 guint8       
1154 g_date_sunday_weeks_in_year (GDateYear  year)
1155 {
1156   GDate d;
1157   
1158   g_return_val_if_fail (g_date_valid_year (year), 0);
1159   
1160   g_date_clear (&d, 1);
1161   g_date_set_dmy (&d, 1, 1, year);
1162   if (g_date_weekday (&d) == G_DATE_SUNDAY) return 53;
1163   g_date_set_dmy (&d, 31, 12, year);
1164   if (g_date_weekday (&d) == G_DATE_SUNDAY) return 53;
1165   if (g_date_is_leap_year (year)) 
1166     {
1167       g_date_set_dmy (&d, 2, 1, year);
1168       if (g_date_weekday (&d) == G_DATE_SUNDAY) return 53;
1169       g_date_set_dmy (&d, 30, 12, year);
1170       if (g_date_weekday (&d) == G_DATE_SUNDAY) return 53;
1171     }
1172   return 52;
1173 }
1174
1175 gint         
1176 g_date_compare (GDate     *lhs, 
1177                 GDate     *rhs)
1178 {
1179   g_return_val_if_fail (lhs != NULL, 0);
1180   g_return_val_if_fail (rhs != NULL, 0);
1181   g_return_val_if_fail (g_date_valid (lhs), 0);
1182   g_return_val_if_fail (g_date_valid (rhs), 0);
1183   
1184   /* Remember the self-comparison case! I think it works right now. */
1185   
1186   while (TRUE)
1187     {
1188       
1189       if (lhs->julian && rhs->julian) 
1190         {
1191           if (lhs->julian_days < rhs->julian_days) return -1;
1192           else if (lhs->julian_days > rhs->julian_days) return 1;
1193           else                                          return 0;
1194         }
1195       else if (lhs->dmy && rhs->dmy) 
1196         {
1197           if (lhs->year < rhs->year)               return -1;
1198           else if (lhs->year > rhs->year)               return 1;
1199           else 
1200             {
1201               if (lhs->month < rhs->month)         return -1;
1202               else if (lhs->month > rhs->month)         return 1;
1203               else 
1204                 {
1205                   if (lhs->day < rhs->day)              return -1;
1206                   else if (lhs->day > rhs->day)              return 1;
1207                   else                                       return 0;
1208                 }
1209               
1210             }
1211           
1212         }
1213       else
1214         {
1215           if (!lhs->julian) g_date_update_julian (lhs);
1216           if (!rhs->julian) g_date_update_julian (rhs);
1217           g_return_val_if_fail (lhs->julian, 0);
1218           g_return_val_if_fail (rhs->julian, 0);
1219         }
1220       
1221     }
1222   return 0; /* warnings */
1223 }
1224
1225
1226 void        
1227 g_date_to_struct_tm (GDate      *d, 
1228                      struct tm   *tm)
1229 {
1230   GDateWeekday day;
1231      
1232   g_return_if_fail (d != NULL);
1233   g_return_if_fail (g_date_valid (d));
1234   g_return_if_fail (tm != NULL);
1235   
1236   if (!d->dmy) 
1237     {
1238       g_date_update_dmy (d);
1239     }
1240   g_return_if_fail (d->dmy);
1241   
1242   /* zero all the irrelevant fields to be sure they're valid */
1243   
1244   /* On Linux and maybe other systems, there are weird non-POSIX
1245    * fields on the end of struct tm that choke strftime if they
1246    * contain garbage.  So we need to 0 the entire struct, not just the
1247    * fields we know to exist. 
1248    */
1249   
1250   memset (tm, 0x0, sizeof (struct tm));
1251   
1252   tm->tm_mday = d->day;
1253   tm->tm_mon  = d->month - 1; /* 0-11 goes in tm */
1254   tm->tm_year = ((int)d->year) - 1900; /* X/Open says tm_year can be negative */
1255   
1256   day = g_date_weekday (d);
1257   if (day == 7) day = 0; /* struct tm wants days since Sunday, so Sunday is 0 */
1258   
1259   tm->tm_wday = (int)day;
1260   
1261   tm->tm_yday = g_date_day_of_year (d) - 1; /* 0 to 365 */
1262   tm->tm_isdst = -1; /* -1 means "information not available" */
1263 }
1264
1265 gsize     
1266 g_date_strftime (gchar       *s, 
1267                  gsize        slen, 
1268                  const gchar *format, 
1269                  GDate       *d)
1270 {
1271   struct tm tm;
1272   gsize retval;
1273   
1274   g_return_val_if_fail (d != NULL, 0);
1275   g_return_val_if_fail (g_date_valid (d), 0);
1276   g_return_val_if_fail (slen > 0, 0); 
1277   g_return_val_if_fail (format != 0, 0);
1278   g_return_val_if_fail (s != 0, 0);
1279   
1280   g_date_to_struct_tm (d, &tm);
1281   
1282   retval = strftime (s, slen, format, &tm);
1283   if (retval == 0)
1284     {
1285       /* If retval == 0, the contents of s are undefined.  We define
1286        *  them. 
1287        */
1288       s[0] = '\0';
1289     }
1290   return retval;
1291 }