summaryrefslogtreecommitdiffstats
path: root/nsprpub/pr/src/misc/prtime.c
blob: 6d711a6b8d1ac97e798a19216ca8bdb0abceb695 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*
 * prtime.c --
 *
 *     NSPR date and time functions
 *
 */

#include "prinit.h"
#include "prtime.h"
#include "prlock.h"
#include "prprf.h"
#include "prlog.h"

#include <string.h>
#include <ctype.h>
#include <errno.h>  /* for EINVAL */
#include <time.h>

/*
 * The COUNT_LEAPS macro counts the number of leap years passed by
 * till the start of the given year Y.  At the start of the year 4
 * A.D. the number of leap years passed by is 0, while at the start of
 * the year 5 A.D. this count is 1. The number of years divisible by
 * 100 but not divisible by 400 (the non-leap years) is deducted from
 * the count to get the correct number of leap years.
 *
 * The COUNT_DAYS macro counts the number of days since 01/01/01 till the
 * start of the given year Y. The number of days at the start of the year
 * 1 is 0 while the number of days at the start of the year 2 is 365
 * (which is ((2)-1) * 365) and so on. The reference point is 01/01/01
 * midnight 00:00:00.
 */

#define COUNT_LEAPS(Y)   ( ((Y)-1)/4 - ((Y)-1)/100 + ((Y)-1)/400 )
#define COUNT_DAYS(Y)  ( ((Y)-1)*365 + COUNT_LEAPS(Y) )
#define DAYS_BETWEEN_YEARS(A, B)  (COUNT_DAYS(B) - COUNT_DAYS(A))

/*
 * Static variables used by functions in this file
 */

/*
 * The following array contains the day of year for the last day of
 * each month, where index 1 is January, and day 0 is January 1.
 */

static const int lastDayOfMonth[2][13] = {
    {-1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364},
    {-1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}
};

/*
 * The number of days in a month
 */

static const PRInt8 nDays[2][12] = {
    {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};

/*
 * Declarations for internal functions defined later in this file.
 */

static void        ComputeGMT(PRTime time, PRExplodedTime *gmt);
static int         IsLeapYear(PRInt16 year);
static void        ApplySecOffset(PRExplodedTime *time, PRInt32 secOffset);

/*
 *------------------------------------------------------------------------
 *
 * ComputeGMT --
 *
 *     Caveats:
 *     - we ignore leap seconds
 *
 *------------------------------------------------------------------------
 */

static void
ComputeGMT(PRTime time, PRExplodedTime *gmt)
{
    PRInt32 tmp, rem;
    PRInt32 numDays;
    PRInt64 numDays64, rem64;
    int isLeap;
    PRInt64 sec;
    PRInt64 usec;
    PRInt64 usecPerSec;
    PRInt64 secPerDay;

    /*
     * We first do the usec, sec, min, hour thing so that we do not
     * have to do LL arithmetic.
     */

    LL_I2L(usecPerSec, 1000000L);
    LL_DIV(sec, time, usecPerSec);
    LL_MOD(usec, time, usecPerSec);
    LL_L2I(gmt->tm_usec, usec);
    /* Correct for weird mod semantics so the remainder is always positive */
    if (gmt->tm_usec < 0) {
        PRInt64 one;

        LL_I2L(one, 1L);
        LL_SUB(sec, sec, one);
        gmt->tm_usec += 1000000L;
    }

    LL_I2L(secPerDay, 86400L);
    LL_DIV(numDays64, sec, secPerDay);
    LL_MOD(rem64, sec, secPerDay);
    /* We are sure both of these numbers can fit into PRInt32 */
    LL_L2I(numDays, numDays64);
    LL_L2I(rem, rem64);
    if (rem < 0) {
        numDays--;
        rem += 86400L;
    }

    /* Compute day of week.  Epoch started on a Thursday. */

    gmt->tm_wday = (numDays + 4) % 7;
    if (gmt->tm_wday < 0) {
        gmt->tm_wday += 7;
    }

    /* Compute the time of day. */

    gmt->tm_hour = rem / 3600;
    rem %= 3600;
    gmt->tm_min = rem / 60;
    gmt->tm_sec = rem % 60;

    /*
     * Compute the year by finding the 400 year period, then working
     * down from there.
     *
     * Since numDays is originally the number of days since January 1, 1970,
     * we must change it to be the number of days from January 1, 0001.
     */

    numDays += 719162;       /* 719162 = days from year 1 up to 1970 */
    tmp = numDays / 146097;  /* 146097 = days in 400 years */
    rem = numDays % 146097;
    gmt->tm_year = tmp * 400 + 1;

    /* Compute the 100 year period. */

    tmp = rem / 36524;    /* 36524 = days in 100 years */
    rem %= 36524;
    if (tmp == 4) {       /* the 400th year is a leap year */
        tmp = 3;
        rem = 36524;
    }
    gmt->tm_year += tmp * 100;

    /* Compute the 4 year period. */

    tmp = rem / 1461;     /* 1461 = days in 4 years */
    rem %= 1461;
    gmt->tm_year += tmp * 4;

    /* Compute which year in the 4. */

    tmp = rem / 365;
    rem %= 365;
    if (tmp == 4) {       /* the 4th year is a leap year */
        tmp = 3;
        rem = 365;
    }

    gmt->tm_year += tmp;
    gmt->tm_yday = rem;
    isLeap = IsLeapYear(gmt->tm_year);

    /* Compute the month and day of month. */

    for (tmp = 1; lastDayOfMonth[isLeap][tmp] < gmt->tm_yday; tmp++) {
    }
    gmt->tm_month = --tmp;
    gmt->tm_mday = gmt->tm_yday - lastDayOfMonth[isLeap][tmp];

    gmt->tm_params.tp_gmt_offset = 0;
    gmt->tm_params.tp_dst_offset = 0;
}


/*
 *------------------------------------------------------------------------
 *
 * PR_ExplodeTime --
 *
 *     Cf. struct tm *gmtime(const time_t *tp) and
 *         struct tm *localtime(const time_t *tp)
 *
 *------------------------------------------------------------------------
 */

PR_IMPLEMENT(void)
PR_ExplodeTime(
    PRTime usecs,
    PRTimeParamFn params,
    PRExplodedTime *exploded)
{
    ComputeGMT(usecs, exploded);
    exploded->tm_params = params(exploded);
    ApplySecOffset(exploded, exploded->tm_params.tp_gmt_offset
                   + exploded->tm_params.tp_dst_offset);
}


/*
 *------------------------------------------------------------------------
 *
 * PR_ImplodeTime --
 *
 *     Cf. time_t mktime(struct tm *tp)
 *     Note that 1 year has < 2^25 seconds.  So an PRInt32 is large enough.
 *
 *------------------------------------------------------------------------
 */
PR_IMPLEMENT(PRTime)
PR_ImplodeTime(const PRExplodedTime *exploded)
{
    PRExplodedTime copy;
    PRTime retVal;
    PRInt64 secPerDay, usecPerSec;
    PRInt64 temp;
    PRInt64 numSecs64;
    PRInt32 numDays;
    PRInt32 numSecs;

    /* Normalize first.  Do this on our copy */
    copy = *exploded;
    PR_NormalizeTime(&copy, PR_GMTParameters);

    numDays = DAYS_BETWEEN_YEARS(1970, copy.tm_year);

    numSecs = copy.tm_yday * 86400 + copy.tm_hour * 3600
              + copy.tm_min * 60 + copy.tm_sec;

    LL_I2L(temp, numDays);
    LL_I2L(secPerDay, 86400);
    LL_MUL(temp, temp, secPerDay);
    LL_I2L(numSecs64, numSecs);
    LL_ADD(numSecs64, numSecs64, temp);

    /* apply the GMT and DST offsets */
    LL_I2L(temp,  copy.tm_params.tp_gmt_offset);
    LL_SUB(numSecs64, numSecs64, temp);
    LL_I2L(temp,  copy.tm_params.tp_dst_offset);
    LL_SUB(numSecs64, numSecs64, temp);

    LL_I2L(usecPerSec, 1000000L);
    LL_MUL(temp, numSecs64, usecPerSec);
    LL_I2L(retVal, copy.tm_usec);
    LL_ADD(retVal, retVal, temp);

    return retVal;
}

/*
 *-------------------------------------------------------------------------
 *
 * IsLeapYear --
 *
 *     Returns 1 if the year is a leap year, 0 otherwise.
 *
 *-------------------------------------------------------------------------
 */

static int IsLeapYear(PRInt16 year)
{
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
        return 1;
    }
    return 0;
}

/*
 * 'secOffset' should be less than 86400 (i.e., a day).
 * 'time' should point to a normalized PRExplodedTime.
 */

static void
ApplySecOffset(PRExplodedTime *time, PRInt32 secOffset)
{
    time->tm_sec += secOffset;

    /* Note that in this implementation we do not count leap seconds */
    if (time->tm_sec < 0 || time->tm_sec >= 60) {
        time->tm_min += time->tm_sec / 60;
        time->tm_sec %= 60;
        if (time->tm_sec < 0) {
            time->tm_sec += 60;
            time->tm_min--;
        }
    }

    if (time->tm_min < 0 || time->tm_min >= 60) {
        time->tm_hour += time->tm_min / 60;
        time->tm_min %= 60;
        if (time->tm_min < 0) {
            time->tm_min += 60;
            time->tm_hour--;
        }
    }

    if (time->tm_hour < 0) {
        /* Decrement mday, yday, and wday */
        time->tm_hour += 24;
        time->tm_mday--;
        time->tm_yday--;
        if (time->tm_mday < 1) {
            time->tm_month--;
            if (time->tm_month < 0) {
                time->tm_month = 11;
                time->tm_year--;
                if (IsLeapYear(time->tm_year)) {
                    time->tm_yday = 365;
                }
                else {
                    time->tm_yday = 364;
                }
            }
            time->tm_mday = nDays[IsLeapYear(time->tm_year)][time->tm_month];
        }
        time->tm_wday--;
        if (time->tm_wday < 0) {
            time->tm_wday = 6;
        }
    } else if (time->tm_hour > 23) {
        /* Increment mday, yday, and wday */
        time->tm_hour -= 24;
        time->tm_mday++;
        time->tm_yday++;
        if (time->tm_mday >
            nDays[IsLeapYear(time->tm_year)][time->tm_month]) {
            time->tm_mday = 1;
            time->tm_month++;
            if (time->tm_month > 11) {
                time->tm_month = 0;
                time->tm_year++;
                time->tm_yday = 0;
            }
        }
        time->tm_wday++;
        if (time->tm_wday > 6) {
            time->tm_wday = 0;
        }
    }
}

PR_IMPLEMENT(void)
PR_NormalizeTime(PRExplodedTime *time, PRTimeParamFn params)
{
    int daysInMonth;
    PRInt32 numDays;

    /* Get back to GMT */
    time->tm_sec -= time->tm_params.tp_gmt_offset
                    + time->tm_params.tp_dst_offset;
    time->tm_params.tp_gmt_offset = 0;
    time->tm_params.tp_dst_offset = 0;

    /* Now normalize GMT */

    if (time->tm_usec < 0 || time->tm_usec >= 1000000) {
        time->tm_sec +=  time->tm_usec / 1000000;
        time->tm_usec %= 1000000;
        if (time->tm_usec < 0) {
            time->tm_usec += 1000000;
            time->tm_sec--;
        }
    }

    /* Note that we do not count leap seconds in this implementation */
    if (time->tm_sec < 0 || time->tm_sec >= 60) {
        time->tm_min += time->tm_sec / 60;
        time->tm_sec %= 60;
        if (time->tm_sec < 0) {
            time->tm_sec += 60;
            time->tm_min--;
        }
    }

    if (time->tm_min < 0 || time->tm_min >= 60) {
        time->tm_hour += time->tm_min / 60;
        time->tm_min %= 60;
        if (time->tm_min < 0) {
            time->tm_min += 60;
            time->tm_hour--;
        }
    }

    if (time->tm_hour < 0 || time->tm_hour >= 24) {
        time->tm_mday += time->tm_hour / 24;
        time->tm_hour %= 24;
        if (time->tm_hour < 0) {
            time->tm_hour += 24;
            time->tm_mday--;
        }
    }

    /* Normalize month and year before mday */
    if (time->tm_month < 0 || time->tm_month >= 12) {
        time->tm_year += time->tm_month / 12;
        time->tm_month %= 12;
        if (time->tm_month < 0) {
            time->tm_month += 12;
            time->tm_year--;
        }
    }

    /* Now that month and year are in proper range, normalize mday */

    if (time->tm_mday < 1) {
        /* mday too small */
        do {
            /* the previous month */
            time->tm_month--;
            if (time->tm_month < 0) {
                time->tm_month = 11;
                time->tm_year--;
            }
            time->tm_mday += nDays[IsLeapYear(time->tm_year)][time->tm_month];
        } while (time->tm_mday < 1);
    } else {
        daysInMonth = nDays[IsLeapYear(time->tm_year)][time->tm_month];
        while (time->tm_mday > daysInMonth) {
            /* mday too large */
            time->tm_mday -= daysInMonth;
            time->tm_month++;
            if (time->tm_month > 11) {
                time->tm_month = 0;
                time->tm_year++;
            }
            daysInMonth = nDays[IsLeapYear(time->tm_year)][time->tm_month];
        }
    }

    /* Recompute yday and wday */
    time->tm_yday = time->tm_mday +
                    lastDayOfMonth[IsLeapYear(time->tm_year)][time->tm_month];

    numDays = DAYS_BETWEEN_YEARS(1970, time->tm_year) + time->tm_yday;
    time->tm_wday = (numDays + 4) % 7;
    if (time->tm_wday < 0) {
        time->tm_wday += 7;
    }

    /* Recompute time parameters */

    time->tm_params = params(time);

    ApplySecOffset(time, time->tm_params.tp_gmt_offset
                   + time->tm_params.tp_dst_offset);
}


/*
 *-------------------------------------------------------------------------
 *
 * PR_LocalTimeParameters --
 *
 *     returns the time parameters for the local time zone
 *
 *     The following uses localtime() from the standard C library.
 *     (time.h)  This is our fallback implementation.  Unix, PC, and BeOS
 *     use this version.  A platform may have its own machine-dependent
 *     implementation of this function.
 *
 *-------------------------------------------------------------------------
 */

#if defined(HAVE_INT_LOCALTIME_R)

/*
 * In this case we could define the macro as
 *     #define MT_safe_localtime(timer, result) \
 *             (localtime_r(timer, result) == 0 ? result : NULL)
 * I chose to compare the return value of localtime_r with -1 so
 * that I can catch the cases where localtime_r returns a pointer
 * to struct tm.  The macro definition above would not be able to
 * detect such mistakes because it is legal to compare a pointer
 * with 0.
 */

#define MT_safe_localtime(timer, result) \
        (localtime_r(timer, result) == -1 ? NULL: result)

#elif defined(HAVE_POINTER_LOCALTIME_R)

#define MT_safe_localtime localtime_r

#elif defined(_MSC_VER)

/* Visual C++ has had localtime_s() since Visual C++ 2005. */

static struct tm *MT_safe_localtime(const time_t *clock, struct tm *result)
{
    errno_t err = localtime_s(result, clock);
    if (err != 0) {
        errno = err;
        return NULL;
    }
    return result;
}

#else

#define HAVE_LOCALTIME_MONITOR 1  /* We use 'monitor' to serialize our calls
                                   * to localtime(). */
static PRLock *monitor = NULL;

static struct tm *MT_safe_localtime(const time_t *clock, struct tm *result)
{
    struct tm *tmPtr;
    int needLock = PR_Initialized();  /* We need to use a lock to protect
                                       * against NSPR threads only when the
                                       * NSPR thread system is activated. */

    if (needLock) {
        PR_Lock(monitor);
    }

    /*
     * Microsoft (all flavors) localtime() returns a NULL pointer if 'clock'
     * represents a time before midnight January 1, 1970.  In
     * that case, we also return a NULL pointer and the struct tm
     * object pointed to by 'result' is not modified.
     *
     * Watcom C/C++ 11.0 localtime() treats time_t as unsigned long
     * hence, does not recognize negative values of clock as pre-1/1/70.
     * We have to manually check (WIN16 only) for negative value of
     * clock and return NULL.
     *
     * With negative values of clock, OS/2 returns the struct tm for
     * clock plus ULONG_MAX. So we also have to check for the invalid
     * structs returned for timezones west of Greenwich when clock == 0.
     */

    tmPtr = localtime(clock);

#if defined(WIN16) || defined(XP_OS2)
    if ( (PRInt32) *clock < 0 ||
         ( (PRInt32) *clock == 0 && tmPtr->tm_year != 70)) {
        result = NULL;
    }
    else {
        *result = *tmPtr;
    }
#else
    if (tmPtr) {
        *result = *tmPtr;
    } else {
        result = NULL;
    }
#endif /* WIN16 */

    if (needLock) {
        PR_Unlock(monitor);
    }

    return result;
}

#endif  /* definition of MT_safe_localtime() */

void _PR_InitTime(void)
{
#ifdef HAVE_LOCALTIME_MONITOR
    monitor = PR_NewLock();
#endif
#ifdef WINCE
    _MD_InitTime();
#endif
}

void _PR_CleanupTime(void)
{
#ifdef HAVE_LOCALTIME_MONITOR
    if (monitor) {
        PR_DestroyLock(monitor);
        monitor = NULL;
    }
#endif
#ifdef WINCE
    _MD_CleanupTime();
#endif
}

#if defined(XP_UNIX) || defined(XP_PC)

PR_IMPLEMENT(PRTimeParameters)
PR_LocalTimeParameters(const PRExplodedTime *gmt)
{

    PRTimeParameters retVal;
    struct tm localTime;
    struct tm *localTimeResult;
    time_t secs;
    PRTime secs64;
    PRInt64 usecPerSec;
    PRInt64 usecPerSec_1;
    PRInt64 maxInt32;
    PRInt64 minInt32;
    PRInt32 dayOffset;
    PRInt32 offset2Jan1970;
    PRInt32 offsetNew;
    int isdst2Jan1970;

    /*
     * Calculate the GMT offset.  First, figure out what is
     * 00:00:00 Jan. 2, 1970 GMT (which is exactly a day, or 86400
     * seconds, since the epoch) in local time.  Then we calculate
     * the difference between local time and GMT in seconds:
     *     gmt_offset = local_time - GMT
     *
     * Caveat: the validity of this calculation depends on two
     * assumptions:
     * 1. Daylight saving time was not in effect on Jan. 2, 1970.
     * 2. The time zone of the geographic location has not changed
     *    since Jan. 2, 1970.
     */

    secs = 86400L;
    localTimeResult = MT_safe_localtime(&secs, &localTime);
    PR_ASSERT(localTimeResult != NULL);
    if (localTimeResult == NULL) {
        /* Shouldn't happen. Use safe fallback for optimized builds. */
        return PR_GMTParameters(gmt);
    }

    /* GMT is 00:00:00, 2nd of Jan. */

    offset2Jan1970 = (PRInt32)localTime.tm_sec
                     + 60L * (PRInt32)localTime.tm_min
                     + 3600L * (PRInt32)localTime.tm_hour
                     + 86400L * (PRInt32)((PRInt32)localTime.tm_mday - 2L);

    isdst2Jan1970 = localTime.tm_isdst;

    /*
     * Now compute DST offset.  We calculate the overall offset
     * of local time from GMT, similar to above.  The overall
     * offset has two components: gmt offset and dst offset.
     * We subtract gmt offset from the overall offset to get
     * the dst offset.
     *     overall_offset = local_time - GMT
     *     overall_offset = gmt_offset + dst_offset
     * ==> dst_offset = local_time - GMT - gmt_offset
     */

    secs64 = PR_ImplodeTime(gmt);    /* This is still in microseconds */
    LL_I2L(usecPerSec, PR_USEC_PER_SEC);
    LL_I2L(usecPerSec_1, PR_USEC_PER_SEC - 1);
    /* Convert to seconds, truncating down (3.1 -> 3 and -3.1 -> -4) */
    if (LL_GE_ZERO(secs64)) {
        LL_DIV(secs64, secs64, usecPerSec);
    } else {
        LL_NEG(secs64, secs64);
        LL_ADD(secs64, secs64, usecPerSec_1);
        LL_DIV(secs64, secs64, usecPerSec);
        LL_NEG(secs64, secs64);
    }
    LL_I2L(maxInt32, PR_INT32_MAX);
    LL_I2L(minInt32, PR_INT32_MIN);
    if (LL_CMP(secs64, >, maxInt32) || LL_CMP(secs64, <, minInt32)) {
        /* secs64 is too large or too small for time_t (32-bit integer) */
        retVal.tp_gmt_offset = offset2Jan1970;
        retVal.tp_dst_offset = 0;
        return retVal;
    }
    LL_L2I(secs, secs64);

    /*
     * On Windows, localtime() (and our MT_safe_localtime() too)
     * returns a NULL pointer for time before midnight January 1,
     * 1970 GMT.  In that case, we just use the GMT offset for
     * Jan 2, 1970 and assume that DST was not in effect.
     */

    if (MT_safe_localtime(&secs, &localTime) == NULL) {
        retVal.tp_gmt_offset = offset2Jan1970;
        retVal.tp_dst_offset = 0;
        return retVal;
    }

    /*
     * dayOffset is the offset between local time and GMT in
     * the day component, which can only be -1, 0, or 1.  We
     * use the day of the week to compute dayOffset.
     */

    dayOffset = (PRInt32) localTime.tm_wday - gmt->tm_wday;

    /*
     * Need to adjust for wrapping around of day of the week from
     * 6 back to 0.
     */

    if (dayOffset == -6) {
        /* Local time is Sunday (0) and GMT is Saturday (6) */
        dayOffset = 1;
    } else if (dayOffset == 6) {
        /* Local time is Saturday (6) and GMT is Sunday (0) */
        dayOffset = -1;
    }

    offsetNew = (PRInt32)localTime.tm_sec - gmt->tm_sec
                + 60L * ((PRInt32)localTime.tm_min - gmt->tm_min)
                + 3600L * ((PRInt32)localTime.tm_hour - gmt->tm_hour)
                + 86400L * (PRInt32)dayOffset;

    if (localTime.tm_isdst <= 0) {
        /* DST is not in effect */
        retVal.tp_gmt_offset = offsetNew;
        retVal.tp_dst_offset = 0;
    } else {
        /* DST is in effect */
        if (isdst2Jan1970 <=0) {
            /*
             * DST was not in effect back in 2 Jan. 1970.
             * Use the offset back then as the GMT offset,
             * assuming the time zone has not changed since then.
             */
            retVal.tp_gmt_offset = offset2Jan1970;
            retVal.tp_dst_offset = offsetNew - offset2Jan1970;
        } else {
            /*
             * DST was also in effect back in 2 Jan. 1970.
             * Then our clever trick (or rather, ugly hack) fails.
             * We will just assume DST offset is an hour.
             */
            retVal.tp_gmt_offset = offsetNew - 3600;
            retVal.tp_dst_offset = 3600;
        }
    }

    return retVal;
}

#endif    /* defined(XP_UNIX) || defined(XP_PC) */

/*
 *------------------------------------------------------------------------
 *
 * PR_USPacificTimeParameters --
 *
 *     The time parameters function for the US Pacific Time Zone.
 *
 *------------------------------------------------------------------------
 */

/*
 * Returns the mday of the first sunday of the month, where
 * mday and wday are for a given day in the month.
 * mdays start with 1 (e.g. 1..31).
 * wdays start with 0 and are in the range 0..6.  0 = Sunday.
 */
#define firstSunday(mday, wday) (((mday - wday + 7 - 1) % 7) + 1)

/*
 * Returns the mday for the N'th Sunday of the month, where
 * mday and wday are for a given day in the month.
 * mdays start with 1 (e.g. 1..31).
 * wdays start with 0 and are in the range 0..6.  0 = Sunday.
 * N has the following values: 0 = first, 1 = second (etc), -1 = last.
 * ndays is the number of days in that month, the same value as the
 * mday of the last day of the month.
 */
static PRInt32
NthSunday(PRInt32 mday, PRInt32 wday, PRInt32 N, PRInt32 ndays)
{
    PRInt32 firstSun = firstSunday(mday, wday);

    if (N < 0) {
        N = (ndays - firstSun) / 7;
    }
    return firstSun + (7 * N);
}

typedef struct DSTParams {
    PRInt8 dst_start_month;       /* 0 = January */
    PRInt8 dst_start_Nth_Sunday;  /* N as defined above */
    PRInt8 dst_start_month_ndays; /* ndays as defined above */
    PRInt8 dst_end_month;         /* 0 = January */
    PRInt8 dst_end_Nth_Sunday;    /* N as defined above */
    PRInt8 dst_end_month_ndays;   /* ndays as defined above */
} DSTParams;

static const DSTParams dstParams[2] = {
    /* year < 2007:  First April Sunday - Last October Sunday */
    { 3, 0, 30, 9, -1, 31 },
    /* year >= 2007: Second March Sunday - First November Sunday */
    { 2, 1, 31, 10, 0, 30 }
};

PR_IMPLEMENT(PRTimeParameters)
PR_USPacificTimeParameters(const PRExplodedTime *gmt)
{
    const DSTParams *dst;
    PRTimeParameters retVal;
    PRExplodedTime st;

    /*
     * Based on geographic location and GMT, figure out offset of
     * standard time from GMT.  In this example implementation, we
     * assume the local time zone is US Pacific Time.
     */

    retVal.tp_gmt_offset = -8L * 3600L;

    /*
     * Make a copy of GMT.  Note that the tm_params field of this copy
     * is ignored.
     */

    st.tm_usec = gmt->tm_usec;
    st.tm_sec = gmt->tm_sec;
    st.tm_min = gmt->tm_min;
    st.tm_hour = gmt->tm_hour;
    st.tm_mday = gmt->tm_mday;
    st.tm_month = gmt->tm_month;
    st.tm_year = gmt->tm_year;
    st.tm_wday = gmt->tm_wday;
    st.tm_yday = gmt->tm_yday;

    /* Apply the offset to GMT to obtain the local standard time */
    ApplySecOffset(&st, retVal.tp_gmt_offset);

    if (st.tm_year < 2007) { /* first April Sunday - Last October Sunday */
        dst = &dstParams[0];
    } else {                 /* Second March Sunday - First November Sunday */
        dst = &dstParams[1];
    }

    /*
     * Apply the rules on standard time or GMT to obtain daylight saving
     * time offset.  In this implementation, we use the US DST rule.
     */
    if (st.tm_month < dst->dst_start_month) {
        retVal.tp_dst_offset = 0L;
    } else if (st.tm_month == dst->dst_start_month) {
        int NthSun = NthSunday(st.tm_mday, st.tm_wday,
                               dst->dst_start_Nth_Sunday,
                               dst->dst_start_month_ndays);
        if (st.tm_mday < NthSun) {              /* Before starting Sunday */
            retVal.tp_dst_offset = 0L;
        } else if (st.tm_mday == NthSun) {      /* Starting Sunday */
            /* 01:59:59 PST -> 03:00:00 PDT */
            if (st.tm_hour < 2) {
                retVal.tp_dst_offset = 0L;
            } else {
                retVal.tp_dst_offset = 3600L;
            }
        } else {                                /* After starting Sunday */
            retVal.tp_dst_offset = 3600L;
        }
    } else if (st.tm_month < dst->dst_end_month) {
        retVal.tp_dst_offset = 3600L;
    } else if (st.tm_month == dst->dst_end_month) {
        int NthSun = NthSunday(st.tm_mday, st.tm_wday,
                               dst->dst_end_Nth_Sunday,
                               dst->dst_end_month_ndays);
        if (st.tm_mday < NthSun) {              /* Before ending Sunday */
            retVal.tp_dst_offset = 3600L;
        } else if (st.tm_mday == NthSun) {      /* Ending Sunday */
            /* 01:59:59 PDT -> 01:00:00 PST */
            if (st.tm_hour < 1) {
                retVal.tp_dst_offset = 3600L;
            } else {
                retVal.tp_dst_offset = 0L;
            }
        } else {                                /* After ending Sunday */
            retVal.tp_dst_offset = 0L;
        }
    } else {
        retVal.tp_dst_offset = 0L;
    }
    return retVal;
}

/*
 *------------------------------------------------------------------------
 *
 * PR_GMTParameters --
 *
 *     Returns the PRTimeParameters for Greenwich Mean Time.
 *     Trivially, both the tp_gmt_offset and tp_dst_offset fields are 0.
 *
 *------------------------------------------------------------------------
 */

PR_IMPLEMENT(PRTimeParameters)
PR_GMTParameters(const PRExplodedTime *gmt)
{
    PRTimeParameters retVal = { 0, 0 };
    return retVal;
}

/*
 * The following code implements PR_ParseTimeString().  It is based on
 * ns/lib/xp/xp_time.c, revision 1.25, by Jamie Zawinski <jwz@netscape.com>.
 */

/*
 * We only recognize the abbreviations of a small subset of time zones
 * in North America, Europe, and Japan.
 *
 * PST/PDT: Pacific Standard/Daylight Time
 * MST/MDT: Mountain Standard/Daylight Time
 * CST/CDT: Central Standard/Daylight Time
 * EST/EDT: Eastern Standard/Daylight Time
 * AST: Atlantic Standard Time
 * NST: Newfoundland Standard Time
 * GMT: Greenwich Mean Time
 * BST: British Summer Time
 * MET: Middle Europe Time
 * EET: Eastern Europe Time
 * JST: Japan Standard Time
 */

typedef enum
{
    TT_UNKNOWN,

    TT_SUN, TT_MON, TT_TUE, TT_WED, TT_THU, TT_FRI, TT_SAT,

    TT_JAN, TT_FEB, TT_MAR, TT_APR, TT_MAY, TT_JUN,
    TT_JUL, TT_AUG, TT_SEP, TT_OCT, TT_NOV, TT_DEC,

    TT_PST, TT_PDT, TT_MST, TT_MDT, TT_CST, TT_CDT, TT_EST, TT_EDT,
    TT_AST, TT_NST, TT_GMT, TT_BST, TT_MET, TT_EET, TT_JST
} TIME_TOKEN;

/*
 * This parses a time/date string into a PRTime
 * (microseconds after "1-Jan-1970 00:00:00 GMT").
 * It returns PR_SUCCESS on success, and PR_FAILURE
 * if the time/date string can't be parsed.
 *
 * Many formats are handled, including:
 *
 *   14 Apr 89 03:20:12
 *   14 Apr 89 03:20 GMT
 *   Fri, 17 Mar 89 4:01:33
 *   Fri, 17 Mar 89 4:01 GMT
 *   Mon Jan 16 16:12 PDT 1989
 *   Mon Jan 16 16:12 +0130 1989
 *   6 May 1992 16:41-JST (Wednesday)
 *   22-AUG-1993 10:59:12.82
 *   22-AUG-1993 10:59pm
 *   22-AUG-1993 12:59am
 *   22-AUG-1993 12:59 PM
 *   Friday, August 04, 1995 3:54 PM
 *   06/21/95 04:24:34 PM
 *   20/06/95 21:07
 *   95-06-08 19:32:48 EDT
 *
 * If the input string doesn't contain a description of the timezone,
 * we consult the `default_to_gmt' to decide whether the string should
 * be interpreted relative to the local time zone (PR_FALSE) or GMT (PR_TRUE).
 * The correct value for this argument depends on what standard specified
 * the time string which you are parsing.
 */

PR_IMPLEMENT(PRStatus)
PR_ParseTimeStringToExplodedTime(
    const char *string,
    PRBool default_to_gmt,
    PRExplodedTime *result)
{
    TIME_TOKEN dotw = TT_UNKNOWN;
    TIME_TOKEN month = TT_UNKNOWN;
    TIME_TOKEN zone = TT_UNKNOWN;
    int zone_offset = -1;
    int dst_offset = 0;
    int date = -1;
    PRInt32 year = -1;
    int hour = -1;
    int min = -1;
    int sec = -1;
    struct tm *localTimeResult;

    const char *rest = string;

    int iterations = 0;

    PR_ASSERT(string && result);
    if (!string || !result) {
        return PR_FAILURE;
    }

    while (*rest)
    {

        if (iterations++ > 1000)
        {
            return PR_FAILURE;
        }

        switch (*rest)
        {
            case 'a': case 'A':
                if (month == TT_UNKNOWN &&
                    (rest[1] == 'p' || rest[1] == 'P') &&
                    (rest[2] == 'r' || rest[2] == 'R')) {
                    month = TT_APR;
                }
                else if (zone == TT_UNKNOWN &&
                         (rest[1] == 's' || rest[1] == 'S') &&
                         (rest[2] == 't' || rest[2] == 'T')) {
                    zone = TT_AST;
                }
                else if (month == TT_UNKNOWN &&
                         (rest[1] == 'u' || rest[1] == 'U') &&
                         (rest[2] == 'g' || rest[2] == 'G')) {
                    month = TT_AUG;
                }
                break;
            case 'b': case 'B':
                if (zone == TT_UNKNOWN &&
                    (rest[1] == 's' || rest[1] == 'S') &&
                    (rest[2] == 't' || rest[2] == 'T')) {
                    zone = TT_BST;
                }
                break;
            case 'c': case 'C':
                if (zone == TT_UNKNOWN &&
                    (rest[1] == 'd' || rest[1] == 'D') &&
                    (rest[2] == 't' || rest[2] == 'T')) {
                    zone = TT_CDT;
                }
                else if (zone == TT_UNKNOWN &&
                         (rest[1] == 's' || rest[1] == 'S') &&
                         (rest[2] == 't' || rest[2] == 'T')) {
                    zone = TT_CST;
                }
                break;
            case 'd': case 'D':
                if (month == TT_UNKNOWN &&
                    (rest[1] == 'e' || rest[1] == 'E') &&
                    (rest[2] == 'c' || rest[2] == 'C')) {
                    month = TT_DEC;
                }
                break;
            case 'e': case 'E':
                if (zone == TT_UNKNOWN &&
                    (rest[1] == 'd' || rest[1] == 'D') &&
                    (rest[2] == 't' || rest[2] == 'T')) {
                    zone = TT_EDT;
                }
                else if (zone == TT_UNKNOWN &&
                         (rest[1] == 'e' || rest[1] == 'E') &&
                         (rest[2] == 't' || rest[2] == 'T')) {
                    zone = TT_EET;
                }
                else if (zone == TT_UNKNOWN &&
                         (rest[1] == 's' || rest[1] == 'S') &&
                         (rest[2] == 't' || rest[2] == 'T')) {
                    zone = TT_EST;
                }
                break;
            case 'f': case 'F':
                if (month == TT_UNKNOWN &&
                    (rest[1] == 'e' || rest[1] == 'E') &&
                    (rest[2] == 'b' || rest[2] == 'B')) {
                    month = TT_FEB;
                }
                else if (dotw == TT_UNKNOWN &&
                         (rest[1] == 'r' || rest[1] == 'R') &&
                         (rest[2] == 'i' || rest[2] == 'I')) {
                    dotw = TT_FRI;
                }
                break;
            case 'g': case 'G':
                if (zone == TT_UNKNOWN &&
                    (rest[1] == 'm' || rest[1] == 'M') &&
                    (rest[2] == 't' || rest[2] == 'T')) {
                    zone = TT_GMT;
                }
                break;
            case 'j': case 'J':
                if (month == TT_UNKNOWN &&
                    (rest[1] == 'a' || rest[1] == 'A') &&
                    (rest[2] == 'n' || rest[2] == 'N')) {
                    month = TT_JAN;
                }
                else if (zone == TT_UNKNOWN &&
                         (rest[1] == 's' || rest[1] == 'S') &&
                         (rest[2] == 't' || rest[2] == 'T')) {
                    zone = TT_JST;
                }
                else if (month == TT_UNKNOWN &&
                         (rest[1] == 'u' || rest[1] == 'U') &&
                         (rest[2] == 'l' || rest[2] == 'L')) {
                    month = TT_JUL;
                }
                else if (month == TT_UNKNOWN &&
                         (rest[1] == 'u' || rest[1] == 'U') &&
                         (rest[2] == 'n' || rest[2] == 'N')) {
                    month = TT_JUN;
                }
                break;
            case 'm': case 'M':
                if (month == TT_UNKNOWN &&
                    (rest[1] == 'a' || rest[1] == 'A') &&
                    (rest[2] == 'r' || rest[2] == 'R')) {
                    month = TT_MAR;
                }
                else if (month == TT_UNKNOWN &&
                         (rest[1] == 'a' || rest[1] == 'A') &&
                         (rest[2] == 'y' || rest[2] == 'Y')) {
                    month = TT_MAY;
                }
                else if (zone == TT_UNKNOWN &&
                         (rest[1] == 'd' || rest[1] == 'D') &&
                         (rest[2] == 't' || rest[2] == 'T')) {
                    zone = TT_MDT;
                }
                else if (zone == TT_UNKNOWN &&
                         (rest[1] == 'e' || rest[1] == 'E') &&
                         (rest[2] == 't' || rest[2] == 'T')) {
                    zone = TT_MET;
                }
                else if (dotw == TT_UNKNOWN &&
                         (rest[1] == 'o' || rest[1] == 'O') &&
                         (rest[2] == 'n' || rest[2] == 'N')) {
                    dotw = TT_MON;
                }
                else if (zone == TT_UNKNOWN &&
                         (rest[1] == 's' || rest[1] == 'S') &&
                         (rest[2] == 't' || rest[2] == 'T')) {
                    zone = TT_MST;
                }
                break;
            case 'n': case 'N':
                if (month == TT_UNKNOWN &&
                    (rest[1] == 'o' || rest[1] == 'O') &&
                    (rest[2] == 'v' || rest[2] == 'V')) {
                    month = TT_NOV;
                }
                else if (zone == TT_UNKNOWN &&
                         (rest[1] == 's' || rest[1] == 'S') &&
                         (rest[2] == 't' || rest[2] == 'T')) {
                    zone = TT_NST;
                }
                break;
            case 'o': case 'O':
                if (month == TT_UNKNOWN &&
                    (rest[1] == 'c' || rest[1] == 'C') &&
                    (rest[2] == 't' || rest[2] == 'T')) {
                    month = TT_OCT;
                }
                break;
            case 'p': case 'P':
                if (zone == TT_UNKNOWN &&
                    (rest[1] == 'd' || rest[1] == 'D') &&
                    (rest[2] == 't' || rest[2] == 'T')) {
                    zone = TT_PDT;
                }
                else if (zone == TT_UNKNOWN &&
                         (rest[1] == 's' || rest[1] == 'S') &&
                         (rest[2] == 't' || rest[2] == 'T')) {
                    zone = TT_PST;
                }
                break;
            case 's': case 'S':
                if (dotw == TT_UNKNOWN &&
                    (rest[1] == 'a' || rest[1] == 'A') &&
                    (rest[2] == 't' || rest[2] == 'T')) {
                    dotw = TT_SAT;
                }
                else if (month == TT_UNKNOWN &&
                         (rest[1] == 'e' || rest[1] == 'E') &&
                         (rest[2] == 'p' || rest[2] == 'P')) {
                    month = TT_SEP;
                }
                else if (dotw == TT_UNKNOWN &&
                         (rest[1] == 'u' || rest[1] == 'U') &&
                         (rest[2] == 'n' || rest[2] == 'N')) {
                    dotw = TT_SUN;
                }
                break;
            case 't': case 'T':
                if (dotw == TT_UNKNOWN &&
                    (rest[1] == 'h' || rest[1] == 'H') &&
                    (rest[2] == 'u' || rest[2] == 'U')) {
                    dotw = TT_THU;
                }
                else if (dotw == TT_UNKNOWN &&
                         (rest[1] == 'u' || rest[1] == 'U') &&
                         (rest[2] == 'e' || rest[2] == 'E')) {
                    dotw = TT_TUE;
                }
                break;
            case 'u': case 'U':
                if (zone == TT_UNKNOWN &&
                    (rest[1] == 't' || rest[1] == 'T') &&
                    !(rest[2] >= 'A' && rest[2] <= 'Z') &&
                    !(rest[2] >= 'a' && rest[2] <= 'z'))
                    /* UT is the same as GMT but UTx is not. */
                {
                    zone = TT_GMT;
                }
                break;
            case 'w': case 'W':
                if (dotw == TT_UNKNOWN &&
                    (rest[1] == 'e' || rest[1] == 'E') &&
                    (rest[2] == 'd' || rest[2] == 'D')) {
                    dotw = TT_WED;
                }
                break;

            case '+': case '-':
            {
                const char *end;
                int sign;
                if (zone_offset != -1)
                {
                    /* already got one... */
                    rest++;
                    break;
                }
                if (zone != TT_UNKNOWN && zone != TT_GMT)
                {
                    /* GMT+0300 is legal, but PST+0300 is not. */
                    rest++;
                    break;
                }

                sign = ((*rest == '+') ? 1 : -1);
                rest++; /* move over sign */
                end = rest;
                while (*end >= '0' && *end <= '9') {
                    end++;
                }
                if (rest == end) { /* no digits here */
                    break;
                }

                if ((end - rest) == 4)
                    /* offset in HHMM */
                    zone_offset = (((((rest[0]-'0')*10) + (rest[1]-'0')) * 60) +
                                   (((rest[2]-'0')*10) + (rest[3]-'0')));
                else if ((end - rest) == 2)
                    /* offset in hours */
                {
                    zone_offset = (((rest[0]-'0')*10) + (rest[1]-'0')) * 60;
                }
                else if ((end - rest) == 1)
                    /* offset in hours */
                {
                    zone_offset = (rest[0]-'0') * 60;
                }
                else
                    /* 3 or >4 */
                {
                    break;
                }

                zone_offset *= sign;
                zone = TT_GMT;
                break;
            }

            case '0': case '1': case '2': case '3': case '4':
            case '5': case '6': case '7': case '8': case '9':
            {
                int tmp_hour = -1;
                int tmp_min = -1;
                int tmp_sec = -1;
                const char *end = rest + 1;
                while (*end >= '0' && *end <= '9') {
                    end++;
                }

                /* end is now the first character after a range of digits. */

                if (*end == ':')
                {
                    if (hour >= 0 && min >= 0) { /* already got it */
                        break;
                    }

                    /* We have seen "[0-9]+:", so this is probably HH:MM[:SS] */
                    if ((end - rest) > 2)
                        /* it is [0-9][0-9][0-9]+: */
                    {
                        break;
                    }
                    if ((end - rest) == 2)
                        tmp_hour = ((rest[0]-'0')*10 +
                                    (rest[1]-'0'));
                    else {
                        tmp_hour = (rest[0]-'0');
                    }

                    /* move over the colon, and parse minutes */

                    rest = ++end;
                    while (*end >= '0' && *end <= '9') {
                        end++;
                    }

                    if (end == rest)
                        /* no digits after first colon? */
                    {
                        break;
                    }
                    if ((end - rest) > 2)
                        /* it is [0-9][0-9][0-9]+: */
                    {
                        break;
                    }
                    if ((end - rest) == 2)
                        tmp_min = ((rest[0]-'0')*10 +
                                   (rest[1]-'0'));
                    else {
                        tmp_min = (rest[0]-'0');
                    }

                    /* now go for seconds */
                    rest = end;
                    if (*rest == ':') {
                        rest++;
                    }
                    end = rest;
                    while (*end >= '0' && *end <= '9') {
                        end++;
                    }

                    if (end == rest)
                        /* no digits after second colon - that's ok. */
                        ;
                    else if ((end - rest) > 2)
                        /* it is [0-9][0-9][0-9]+: */
                    {
                        break;
                    }
                    if ((end - rest) == 2)
                        tmp_sec = ((rest[0]-'0')*10 +
                                   (rest[1]-'0'));
                    else {
                        tmp_sec = (rest[0]-'0');
                    }

                    /* If we made it here, we've parsed hour and min,
                       and possibly sec, so it worked as a unit. */

                    /* skip over whitespace and see if there's an AM or PM
                       directly following the time.
                     */
                    if (tmp_hour <= 12)
                    {
                        const char *s = end;
                        while (*s && (*s == ' ' || *s == '\t')) {
                            s++;
                        }
                        if ((s[0] == 'p' || s[0] == 'P') &&
                            (s[1] == 'm' || s[1] == 'M'))
                            /* 10:05pm == 22:05, and 12:05pm == 12:05 */
                        {
                            tmp_hour = (tmp_hour == 12 ? 12 : tmp_hour + 12);
                        }
                        else if (tmp_hour == 12 &&
                                 (s[0] == 'a' || s[0] == 'A') &&
                                 (s[1] == 'm' || s[1] == 'M'))
                            /* 12:05am == 00:05 */
                        {
                            tmp_hour = 0;
                        }
                    }

                    hour = tmp_hour;
                    min = tmp_min;
                    sec = tmp_sec;
                    rest = end;
                    break;
                }
                if ((*end == '/' || *end == '-') &&
                    end[1] >= '0' && end[1] <= '9')
                {
                    /* Perhaps this is 6/16/95, 16/6/95, 6-16-95, or 16-6-95
                       or even 95-06-05...
                       #### But it doesn't handle 1995-06-22.
                     */
                    int n1, n2, n3;
                    const char *s;

                    if (month != TT_UNKNOWN)
                        /* if we saw a month name, this can't be. */
                    {
                        break;
                    }

                    s = rest;

                    n1 = (*s++ - '0');                                /* first 1 or 2 digits */
                    if (*s >= '0' && *s <= '9') {
                        n1 = n1*10 + (*s++ - '0');
                    }

                    if (*s != '/' && *s != '-') {              /* slash */
                        break;
                    }
                    s++;

                    if (*s < '0' || *s > '9') {              /* second 1 or 2 digits */
                        break;
                    }
                    n2 = (*s++ - '0');
                    if (*s >= '0' && *s <= '9') {
                        n2 = n2*10 + (*s++ - '0');
                    }

                    if (*s != '/' && *s != '-') {              /* slash */
                        break;
                    }
                    s++;

                    if (*s < '0' || *s > '9') {              /* third 1, 2, 4, or 5 digits */
                        break;
                    }
                    n3 = (*s++ - '0');
                    if (*s >= '0' && *s <= '9') {
                        n3 = n3*10 + (*s++ - '0');
                    }

                    if (*s >= '0' && *s <= '9')            /* optional digits 3, 4, and 5 */
                    {
                        n3 = n3*10 + (*s++ - '0');
                        if (*s < '0' || *s > '9') {
                            break;
                        }
                        n3 = n3*10 + (*s++ - '0');
                        if (*s >= '0' && *s <= '9') {
                            n3 = n3*10 + (*s++ - '0');
                        }
                    }

                    if ((*s >= '0' && *s <= '9') ||        /* followed by non-alphanum */
                        (*s >= 'A' && *s <= 'Z') ||
                        (*s >= 'a' && *s <= 'z')) {
                        break;
                    }

                    /* Ok, we parsed three 1-2 digit numbers, with / or -
                       between them.  Now decide what the hell they are
                       (DD/MM/YY or MM/DD/YY or YY/MM/DD.)
                     */

                    if (n1 > 31 || n1 == 0)  /* must be YY/MM/DD */
                    {
                        if (n2 > 12) {
                            break;
                        }
                        if (n3 > 31) {
                            break;
                        }
                        year = n1;
                        if (year < 70) {
                            year += 2000;
                        }
                        else if (year < 100) {
                            year += 1900;
                        }
                        month = (TIME_TOKEN)(n2 + ((int)TT_JAN) - 1);
                        date = n3;
                        rest = s;
                        break;
                    }

                    if (n1 > 12 && n2 > 12)  /* illegal */
                    {
                        rest = s;
                        break;
                    }

                    if (n3 < 70) {
                        n3 += 2000;
                    }
                    else if (n3 < 100) {
                        n3 += 1900;
                    }

                    if (n1 > 12)  /* must be DD/MM/YY */
                    {
                        date = n1;
                        month = (TIME_TOKEN)(n2 + ((int)TT_JAN) - 1);
                        year = n3;
                    }
                    else                  /* assume MM/DD/YY */
                    {
                        /* #### In the ambiguous case, should we consult the
                           locale to find out the local default? */
                        month = (TIME_TOKEN)(n1 + ((int)TT_JAN) - 1);
                        date = n2;
                        year = n3;
                    }
                    rest = s;
                }
                else if ((*end >= 'A' && *end <= 'Z') ||
                         (*end >= 'a' && *end <= 'z'))
                    /* Digits followed by non-punctuation - what's that? */
                    ;
                else if ((end - rest) == 5)                /* five digits is a year */
                    year = (year < 0
                            ? ((rest[0]-'0')*10000L +
                               (rest[1]-'0')*1000L +
                               (rest[2]-'0')*100L +
                               (rest[3]-'0')*10L +
                               (rest[4]-'0'))
                            : year);
                else if ((end - rest) == 4)                /* four digits is a year */
                    year = (year < 0
                            ? ((rest[0]-'0')*1000L +
                               (rest[1]-'0')*100L +
                               (rest[2]-'0')*10L +
                               (rest[3]-'0'))
                            : year);
                else if ((end - rest) == 2)                /* two digits - date or year */
                {
                    int n = ((rest[0]-'0')*10 +
                             (rest[1]-'0'));
                    /* If we don't have a date (day of the month) and we see a number
                         less than 32, then assume that is the date.

                             Otherwise, if we have a date and not a year, assume this is the
                             year.  If it is less than 70, then assume it refers to the 21st
                             century.  If it is two digits (>= 70), assume it refers to this
                             century.  Otherwise, assume it refers to an unambiguous year.

                             The world will surely end soon.
                       */
                    if (date < 0 && n < 32) {
                        date = n;
                    }
                    else if (year < 0)
                    {
                        if (n < 70) {
                            year = 2000 + n;
                        }
                        else if (n < 100) {
                            year = 1900 + n;
                        }
                        else {
                            year = n;
                        }
                    }
                    /* else what the hell is this. */
                }
                else if ((end - rest) == 1) {              /* one digit - date */
                    date = (date < 0 ? (rest[0]-'0') : date);
                }
                /* else, three or more than five digits - what's that? */

                break;
            }
        }

        /* Skip to the end of this token, whether we parsed it or not.
               Tokens are delimited by whitespace, or ,;-/
               But explicitly not :+-.
         */
        while (*rest &&
               *rest != ' ' && *rest != '\t' &&
               *rest != ',' && *rest != ';' &&
               *rest != '-' && *rest != '+' &&
               *rest != '/' &&
               *rest != '(' && *rest != ')' && *rest != '[' && *rest != ']') {
            rest++;
        }
        /* skip over uninteresting chars. */
SKIP_MORE:
        while (*rest &&
               (*rest == ' ' || *rest == '\t' ||
                *rest == ',' || *rest == ';' || *rest == '/' ||
                *rest == '(' || *rest == ')' || *rest == '[' || *rest == ']')) {
            rest++;
        }

        /* "-" is ignored at the beginning of a token if we have not yet
               parsed a year (e.g., the second "-" in "30-AUG-1966"), or if
               the character after the dash is not a digit. */
        if (*rest == '-' && ((rest > string &&
                              isalpha((unsigned char)rest[-1]) && year < 0) ||
                             rest[1] < '0' || rest[1] > '9'))
        {
            rest++;
            goto SKIP_MORE;
        }

    }

    if (zone != TT_UNKNOWN && zone_offset == -1)
    {
        switch (zone)
        {
            case TT_PST: zone_offset = -8 * 60; break;
            case TT_PDT: zone_offset = -8 * 60; dst_offset = 1 * 60; break;
            case TT_MST: zone_offset = -7 * 60; break;
            case TT_MDT: zone_offset = -7 * 60; dst_offset = 1 * 60; break;
            case TT_CST: zone_offset = -6 * 60; break;
            case TT_CDT: zone_offset = -6 * 60; dst_offset = 1 * 60; break;
            case TT_EST: zone_offset = -5 * 60; break;
            case TT_EDT: zone_offset = -5 * 60; dst_offset = 1 * 60; break;
            case TT_AST: zone_offset = -4 * 60; break;
            case TT_NST: zone_offset = -3 * 60 - 30; break;
            case TT_GMT: zone_offset =  0 * 60; break;
            case TT_BST: zone_offset =  0 * 60; dst_offset = 1 * 60; break;
            case TT_MET: zone_offset =  1 * 60; break;
            case TT_EET: zone_offset =  2 * 60; break;
            case TT_JST: zone_offset =  9 * 60; break;
            default:
                PR_ASSERT (0);
                break;
        }
    }

    /* If we didn't find a year, month, or day-of-the-month, we can't
           possibly parse this, and in fact, mktime() will do something random
           (I'm seeing it return "Tue Feb  5 06:28:16 2036", which is no doubt
           a numerologically significant date... */
    if (month == TT_UNKNOWN || date == -1 || year == -1 || year > PR_INT16_MAX) {
        return PR_FAILURE;
    }

    memset(result, 0, sizeof(*result));
    if (sec != -1) {
        result->tm_sec = sec;
    }
    if (min != -1) {
        result->tm_min = min;
    }
    if (hour != -1) {
        result->tm_hour = hour;
    }
    if (date != -1) {
        result->tm_mday = date;
    }
    if (month != TT_UNKNOWN) {
        result->tm_month = (((int)month) - ((int)TT_JAN));
    }
    if (year != -1) {
        result->tm_year = year;
    }
    if (dotw != TT_UNKNOWN) {
        result->tm_wday = (((int)dotw) - ((int)TT_SUN));
    }
    /*
     * Mainly to compute wday and yday, but normalized time is also required
     * by the check below that works around a Visual C++ 2005 mktime problem.
     */
    PR_NormalizeTime(result, PR_GMTParameters);
    /* The remaining work is to set the gmt and dst offsets in tm_params. */

    if (zone == TT_UNKNOWN && default_to_gmt)
    {
        /* No zone was specified, so pretend the zone was GMT. */
        zone = TT_GMT;
        zone_offset = 0;
    }

    if (zone_offset == -1)
    {
        /* no zone was specified, and we're to assume that everything
          is local. */
        struct tm localTime;
        time_t secs;

        PR_ASSERT(result->tm_month > -1 &&
                  result->tm_mday > 0 &&
                  result->tm_hour > -1 &&
                  result->tm_min > -1 &&
                  result->tm_sec > -1);

        /*
         * To obtain time_t from a tm structure representing the local
         * time, we call mktime().  However, we need to see if we are
         * on 1-Jan-1970 or before.  If we are, we can't call mktime()
         * because mktime() will crash on win16. In that case, we
         * calculate zone_offset based on the zone offset at
         * 00:00:00, 2 Jan 1970 GMT, and subtract zone_offset from the
         * date we are parsing to transform the date to GMT.  We also
         * do so if mktime() returns (time_t) -1 (time out of range).
        */

        /* month, day, hours, mins and secs are always non-negative
           so we dont need to worry about them. */
        if(result->tm_year >= 1970)
        {
            PRInt64 usec_per_sec;

            localTime.tm_sec = result->tm_sec;
            localTime.tm_min = result->tm_min;
            localTime.tm_hour = result->tm_hour;
            localTime.tm_mday = result->tm_mday;
            localTime.tm_mon = result->tm_month;
            localTime.tm_year = result->tm_year - 1900;
            /* Set this to -1 to tell mktime "I don't care".  If you set
               it to 0 or 1, you are making assertions about whether the
               date you are handing it is in daylight savings mode or not;
               and if you're wrong, it will "fix" it for you. */
            localTime.tm_isdst = -1;

#if _MSC_VER == 1400  /* 1400 = Visual C++ 2005 (8.0) */
            /*
             * mktime will return (time_t) -1 if the input is a date
             * after 23:59:59, December 31, 3000, US Pacific Time (not
             * UTC as documented):
             * http://msdn.microsoft.com/en-us/library/d1y53h2a(VS.80).aspx
             * But if the year is 3001, mktime also invokes the invalid
             * parameter handler, causing the application to crash.  This
             * problem has been reported in
             * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=266036.
             * We avoid this crash by not calling mktime if the date is
             * out of range.  To use a simple test that works in any time
             * zone, we consider year 3000 out of range as well.  (See
             * bug 480740.)
             */
            if (result->tm_year >= 3000) {
                /* Emulate what mktime would have done. */
                errno = EINVAL;
                secs = (time_t) -1;
            } else {
                secs = mktime(&localTime);
            }
#else
            secs = mktime(&localTime);
#endif
            if (secs != (time_t) -1)
            {
                PRTime usecs64;
                LL_I2L(usecs64, secs);
                LL_I2L(usec_per_sec, PR_USEC_PER_SEC);
                LL_MUL(usecs64, usecs64, usec_per_sec);
                PR_ExplodeTime(usecs64, PR_LocalTimeParameters, result);
                return PR_SUCCESS;
            }
        }

        /* So mktime() can't handle this case.  We assume the
           zone_offset for the date we are parsing is the same as
           the zone offset on 00:00:00 2 Jan 1970 GMT. */
        secs = 86400;
        localTimeResult = MT_safe_localtime(&secs, &localTime);
        PR_ASSERT(localTimeResult != NULL);
        if (localTimeResult == NULL) {
            return PR_FAILURE;
        }
        zone_offset = localTime.tm_min
                      + 60 * localTime.tm_hour
                      + 1440 * (localTime.tm_mday - 2);
    }

    result->tm_params.tp_gmt_offset = zone_offset * 60;
    result->tm_params.tp_dst_offset = dst_offset * 60;

    return PR_SUCCESS;
}

PR_IMPLEMENT(PRStatus)
PR_ParseTimeString(
    const char *string,
    PRBool default_to_gmt,
    PRTime *result)
{
    PRExplodedTime tm;
    PRStatus rv;

    rv = PR_ParseTimeStringToExplodedTime(string,
                                          default_to_gmt,
                                          &tm);
    if (rv != PR_SUCCESS) {
        return rv;
    }

    *result = PR_ImplodeTime(&tm);

    return PR_SUCCESS;
}

/*
 *******************************************************************
 *******************************************************************
 **
 **    OLD COMPATIBILITY FUNCTIONS
 **
 *******************************************************************
 *******************************************************************
 */


/*
 *-----------------------------------------------------------------------
 *
 * PR_FormatTime --
 *
 *     Format a time value into a buffer. Same semantics as strftime().
 *
 *-----------------------------------------------------------------------
 */

PR_IMPLEMENT(PRUint32)
PR_FormatTime(char *buf, int buflen, const char *fmt,
              const PRExplodedTime *time)
{
    size_t rv;
    struct tm a;
    struct tm *ap;

    if (time) {
        ap = &a;
        a.tm_sec = time->tm_sec;
        a.tm_min = time->tm_min;
        a.tm_hour = time->tm_hour;
        a.tm_mday = time->tm_mday;
        a.tm_mon = time->tm_month;
        a.tm_wday = time->tm_wday;
        a.tm_year = time->tm_year - 1900;
        a.tm_yday = time->tm_yday;
        a.tm_isdst = time->tm_params.tp_dst_offset ? 1 : 0;

        /*
         * On some platforms, for example SunOS 4, struct tm has two
         * additional fields: tm_zone and tm_gmtoff.
         */

#if (__GLIBC__ >= 2) || defined(NETBSD) \
        || defined(OPENBSD) || defined(FREEBSD) \
        || defined(DARWIN) || defined(ANDROID)
        a.tm_zone = NULL;
        a.tm_gmtoff = time->tm_params.tp_gmt_offset +
                      time->tm_params.tp_dst_offset;
#endif
    } else {
        ap = NULL;
    }

    rv = strftime(buf, buflen, fmt, ap);
    if (!rv && buf && buflen > 0) {
        /*
         * When strftime fails, the contents of buf are indeterminate.
         * Some callers don't check the return value from this function,
         * so store an empty string in buf in case they try to print it.
         */
        buf[0] = '\0';
    }
    return rv;
}


/*
 * The following string arrays and macros are used by PR_FormatTimeUSEnglish().
 */

static const char* abbrevDays[] =
{
    "Sun","Mon","Tue","Wed","Thu","Fri","Sat"
};

static const char* days[] =
{
    "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"
};

static const char* abbrevMonths[] =
{
    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

static const char* months[] =
{
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
};


/*
 * Add a single character to the given buffer, incrementing the buffer pointer
 * and decrementing the buffer size. Return 0 on error.
 */
#define ADDCHAR( buf, bufSize, ch )             \
do                                              \
{                                               \
   if( bufSize < 1 )                            \
   {                                            \
      *(--buf) = '\0';                          \
      return 0;                                 \
   }                                            \
   *buf++ = ch;                                 \
   bufSize--;                                   \
}                                               \
while(0)


/*
 * Add a string to the given buffer, incrementing the buffer pointer
 * and decrementing the buffer size appropriately.  Return 0 on error.
 */
#define ADDSTR( buf, bufSize, str )             \
do                                              \
{                                               \
   PRUint32 strSize = strlen( str );              \
   if( strSize > bufSize )                      \
   {                                            \
      if( bufSize==0 )                          \
         *(--buf) = '\0';                       \
      else                                      \
         *buf = '\0';                           \
      return 0;                                 \
   }                                            \
   memcpy(buf, str, strSize);                   \
   buf += strSize;                              \
   bufSize -= strSize;                          \
}                                               \
while(0)

/* Needed by PR_FormatTimeUSEnglish() */
static unsigned int  pr_WeekOfYear(const PRExplodedTime* time,
                                   unsigned int firstDayOfWeek);


/***********************************************************************************
 *
 * Description:
 *  This is a dumbed down version of strftime that will format the date in US
 *  English regardless of the setting of the global locale.  This functionality is
 *  needed to write things like MIME headers which must always be in US English.
 *
 **********************************************************************************/

PR_IMPLEMENT(PRUint32)
PR_FormatTimeUSEnglish( char* buf, PRUint32 bufSize,
                        const char* format, const PRExplodedTime* time )
{
    char*         bufPtr = buf;
    const char*   fmtPtr;
    char          tmpBuf[ 40 ];
    const int     tmpBufSize = sizeof( tmpBuf );


    for( fmtPtr=format; *fmtPtr != '\0'; fmtPtr++ )
    {
        if( *fmtPtr != '%' )
        {
            ADDCHAR( bufPtr, bufSize, *fmtPtr );
        }
        else
        {
            switch( *(++fmtPtr) )
            {
                case '%':
                    /* escaped '%' character */
                    ADDCHAR( bufPtr, bufSize, '%' );
                    break;

                case 'a':
                    /* abbreviated weekday name */
                    ADDSTR( bufPtr, bufSize, abbrevDays[ time->tm_wday ] );
                    break;

                case 'A':
                    /* full weekday name */
                    ADDSTR( bufPtr, bufSize, days[ time->tm_wday ] );
                    break;

                case 'b':
                    /* abbreviated month name */
                    ADDSTR( bufPtr, bufSize, abbrevMonths[ time->tm_month ] );
                    break;

                case 'B':
                    /* full month name */
                    ADDSTR(bufPtr, bufSize,  months[ time->tm_month ] );
                    break;

                case 'c':
                    /* Date and time. */
                    PR_FormatTimeUSEnglish( tmpBuf, tmpBufSize, "%a %b %d %H:%M:%S %Y", time );
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                case 'd':
                    /* day of month ( 01 - 31 ) */
                    PR_snprintf(tmpBuf,tmpBufSize,"%.2ld",time->tm_mday );
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                case 'H':
                    /* hour ( 00 - 23 ) */
                    PR_snprintf(tmpBuf,tmpBufSize,"%.2ld",time->tm_hour );
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                case 'I':
                    /* hour ( 01 - 12 ) */
                    PR_snprintf(tmpBuf,tmpBufSize,"%.2ld",
                                (time->tm_hour%12) ? time->tm_hour%12 : (PRInt32) 12 );
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                case 'j':
                    /* day number of year ( 001 - 366 ) */
                    PR_snprintf(tmpBuf,tmpBufSize,"%.3d",time->tm_yday + 1);
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                case 'm':
                    /* month number ( 01 - 12 ) */
                    PR_snprintf(tmpBuf,tmpBufSize,"%.2ld",time->tm_month+1);
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                case 'M':
                    /* minute ( 00 - 59 ) */
                    PR_snprintf(tmpBuf,tmpBufSize,"%.2ld",time->tm_min );
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                case 'p':
                    /* locale's equivalent of either AM or PM */
                    ADDSTR( bufPtr, bufSize, (time->tm_hour<12)?"AM":"PM" );
                    break;

                case 'S':
                    /* seconds ( 00 - 61 ), allows for leap seconds */
                    PR_snprintf(tmpBuf,tmpBufSize,"%.2ld",time->tm_sec );
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                case 'U':
                    /* week number of year ( 00 - 53  ),  Sunday  is  the first day of week 1 */
                    PR_snprintf(tmpBuf,tmpBufSize,"%.2d", pr_WeekOfYear( time, 0 ) );
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                case 'w':
                    /* weekday number ( 0 - 6 ), Sunday = 0 */
                    PR_snprintf(tmpBuf,tmpBufSize,"%d",time->tm_wday );
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                case 'W':
                    /* Week number of year ( 00 - 53  ),  Monday  is  the first day of week 1 */
                    PR_snprintf(tmpBuf,tmpBufSize,"%.2d", pr_WeekOfYear( time, 1 ) );
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                case 'x':
                    /* Date representation */
                    PR_FormatTimeUSEnglish( tmpBuf, tmpBufSize, "%m/%d/%y", time );
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                case 'X':
                    /* Time representation. */
                    PR_FormatTimeUSEnglish( tmpBuf, tmpBufSize, "%H:%M:%S", time );
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                case 'y':
                    /* year within century ( 00 - 99 ) */
                    PR_snprintf(tmpBuf,tmpBufSize,"%.2d",time->tm_year % 100 );
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                case 'Y':
                    /* year as ccyy ( for example 1986 ) */
                    PR_snprintf(tmpBuf,tmpBufSize,"%.4d",time->tm_year );
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                case 'Z':
                    /* Time zone name or no characters if  no  time  zone exists.
                     * Since time zone name is supposed to be independant of locale, we
                     * defer to PR_FormatTime() for this option.
                     */
                    PR_FormatTime( tmpBuf, tmpBufSize, "%Z", time );
                    ADDSTR( bufPtr, bufSize, tmpBuf );
                    break;

                default:
                    /* Unknown format.  Simply copy format into output buffer. */
                    ADDCHAR( bufPtr, bufSize, '%' );
                    ADDCHAR( bufPtr, bufSize, *fmtPtr );
                    break;

            }
        }
    }

    ADDCHAR( bufPtr, bufSize, '\0' );
    return (PRUint32)(bufPtr - buf - 1);
}



/***********************************************************************************
 *
 * Description:
 *  Returns the week number of the year (0-53) for the given time.  firstDayOfWeek
 *  is the day on which the week is considered to start (0=Sun, 1=Mon, ...).
 *  Week 1 starts the first time firstDayOfWeek occurs in the year.  In other words,
 *  a partial week at the start of the year is considered week 0.
 *
 **********************************************************************************/

static unsigned int
pr_WeekOfYear(const PRExplodedTime* time, unsigned int firstDayOfWeek)
{
    int dayOfWeek;
    int dayOfYear;

    /* Get the day of the year for the given time then adjust it to represent the
     * first day of the week containing the given time.
     */
    dayOfWeek = time->tm_wday - firstDayOfWeek;
    if (dayOfWeek < 0) {
        dayOfWeek += 7;
    }

    dayOfYear = time->tm_yday - dayOfWeek;

    if( dayOfYear <= 0 )
    {
        /* If dayOfYear is <= 0, it is in the first partial week of the year. */
        return 0;
    }

    /* Count the number of full weeks ( dayOfYear / 7 ) then add a week if there
     * are any days left over ( dayOfYear % 7 ).  Because we are only counting to
     * the first day of the week containing the given time, rather than to the
     * actual day representing the given time, any days in week 0 will be "absorbed"
     * as extra days in the given week.
     */
    return (dayOfYear / 7) + ( (dayOfYear % 7) == 0 ? 0 : 1 );

}