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
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
|
#----------------------------------------------------------------------
#
# clock.tcl --
#
# This file implements the portions of the [clock] ensemble that
# are coded in Tcl. Refer to the users' manual to see the description
# of the [clock] command and its subcommands.
#
#
#----------------------------------------------------------------------
#
# Copyright (c) 2004 by Kevin B. Kenny. All rights reserved.
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
# RCS: @(#) $Id: clock.tcl,v 1.4 2004/09/07 17:38:56 kennykb Exp $
#
#----------------------------------------------------------------------
# We must have message catalogs that support the root locale, and
# we need access to the Registry on Windows systems. We also need
# Tcl 8.5 dictionaries.
uplevel \#0 {
package require msgcat 1.4
if { $::tcl_platform(platform) eq {windows} } {
if { [catch { package require registry 1.1 }] } {
# HIDEOUS KLUDGE: [package require registry 1.1] has failed.
# This failure likely means that we're running in Tcl's build
# directory instead of the install directory. We recover by
# trying to load tclreg*.dll directly.
if { [catch {
load [lindex \
[glob -directory \
[file join \
[pwd] \
[file dirname [info nameofexecutable]]] \
tclReg*.dll] \
0] registry
}] } {
# Still no registry!
namespace eval ::tcl::clock [list variable NoRegistry {}]
}
}
}
}
# Put the library directory into the namespace for the ensemble
# so that the library code can find message catalogs and time zone
# definition files.
namespace eval ::tcl::clock \
[list variable LibDir [file dirname [info script]]]
#----------------------------------------------------------------------
#
# clock --
#
# Manipulate times.
#
# The 'clock' command manipulates time. Refer to the user documentation
# for the available subcommands and what they do.
#
#----------------------------------------------------------------------
namespace eval ::tcl::clock {
# Export the subcommands
namespace export format
namespace export clicks
namespace export microseconds
namespace export milliseconds
namespace export scan
namespace export seconds
namespace export add
# Import the message catalog commands that we use.
namespace import ::msgcat::mc
namespace import ::msgcat::mcload
namespace import ::msgcat::mclocale
# Define the Greenwich time zone
proc initTZData {} {
variable TZData
array unset TZData
set TZData(:Etc/GMT) {
{-9223372036854775808 0 0 GMT}
}
set TZData(:GMT) $TZData(:Etc/GMT)
set TZData(:Etc/UTC) {
{-9223372036854775808 0 0 UTC}
}
set TZData(:UTC) $TZData(:Etc/UTC)
}
initTZData
# Define the message catalog for the root locale.
::msgcat::mcmset {} {
AM {am}
BCE {B.C.E.}
CE {C.E.}
DATE_FORMAT {%m/%d/%Y}
DATE_TIME_FORMAT {%a %b %e %H:%M:%S %Y}
DAYS_OF_WEEK_ABBREV {
Sun Mon Tue Wed Thu Fri Sat
}
DAYS_OF_WEEK_FULL {
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
}
GREGORIAN_CHANGE_DATE 2299161
LOCALE_DATE_FORMAT {%m/%d/%Y}
LOCALE_DATE_TIME_FORMAT {%a %b %e %H:%M:%S %Y}
LOCALE_ERAS {}
LOCALE_NUMERALS {
00 01 02 03 04 05 06 07 08 09
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
}
LOCALE_TIME_FORMAT {%H:%M:%S}
LOCALE_YEAR_FORMAT {%EC%Ey}
MONTHS_ABBREV {
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
}
MONTHS_FULL {
January February March
April May June
July August September
October November December
}
PM {pm}
TIME_FORMAT {%H:%M:%S}
TIME_FORMAT_12 {%I:%M:%S %P}
TIME_FORMAT_24 {%H:%M}
TIME_FORMAT_24_SECS {%H:%M:%S}
}
# Define a few Gregorian change dates for other locales. In most cases
# the change date follows a language, because a nation's colonies changed
# at the same time as the nation itself. In many cases, different
# national boundaries existed; the dominating rule is to follow the
# nation's capital.
# Italy, Spain, Portugal, Poland
::msgcat::mcset it GREGORIAN_CHANGE_DATE 2299161
::msgcat::mcset es GREGORIAN_CHANGE_DATE 2299161
::msgcat::mcset pt GREGORIAN_CHANGE_DATE 2299161
::msgcat::mcset pl GREGORIAN_CHANGE_DATE 2299161
# France, Austria
::msgcat::mcset fr GREGORIAN_CHANGE_DATE 2299227
# For Belgium, we follow Southern Netherlands; Liege Diocese
# changed several weeks later.
::msgcat::mcset fr_BE GREGORIAN_CHANGE_DATE 2299238
::msgcat::mcset nl_BE GREGORIAN_CHANGE_DATE 2299238
# Austria
::msgcat::mcset de_AT GREGORIAN_CHANGE_DATE 2299527
# Hungary
::msgcat::mcset hu GREGORIAN_CHANGE_DATE 2301004
# Germany, Norway, Denmark (Catholic Germany changed earlier)
::msgcat::mcset de_DE GREGORIAN_CHANGE_DATE 2342032
::msgcat::mcset nb GREGORIAN_CHANGE_DATE 2342032
::msgcat::mcset nn GREGORIAN_CHANGE_DATE 2342032
::msgcat::mcset no GREGORIAN_CHANGE_DATE 2342032
::msgcat::mcset da GREGORIAN_CHANGE_DATE 2342032
# Holland (Brabant, Gelderland, Flanders, Friesland, etc. changed
# at various times)
::msgcat::mcset nl GREGORIAN_CHANGE_DATE 2342165
# Protestant Switzerland (Catholic cantons changed earlier)
::msgcat::mcset fr_CH GREGORIAN_CHANGE_DATE 2361342
::msgcat::mcset it_CH GREGORIAN_CHANGE_DATE 2361342
::msgcat::mcset de_CH GREGORIAN_CHANGE_DATE 2361342
# English speaking countries
::msgcat::mcset en GREGORIAN_CHANGE_DATE 2361222
# Sweden (had several changes onto and off of the Gregorian calendar)
::msgcat::mcset sv GREGORIAN_CHANGE_DATE 2361390
# Russia
::msgcat::mcset ru GREGORIAN_CHANGE_DATE 2421639
# Romania (Transylvania changed earler - perhaps de_RO should show
# the earlier date?)
::msgcat::mcset ro GREGORIAN_CHANGE_DATE 2422063
# Greece
::msgcat::mcset el GREGORIAN_CHANGE_DATE 2423480
#------------------------------------------------------------------
#
# CONSTANTS
#
#------------------------------------------------------------------
# Paths at which binary time zone data for the Olson libraries
# are known to reside on various operating systems
variable ZoneinfoPaths {}
proc ZoneinfoInit {} {
variable ZoneinfoPaths
rename ZoneinfoInit {}
foreach path {
/usr/share/zoneinfo
/usr/share/lib/zoneinfo
/usr/local/etc/zoneinfo
C:/Progra~1/cygwin/usr/local/etc/zoneinfo
} {
if { [file isdirectory $path] } {
lappend ZoneinfoPaths $path
}
}
}
ZoneinfoInit
# Define the directories for time zone data and message catalogs.
variable DataDir [file join $LibDir tzdata]
variable MsgDir [file join $LibDir msgs]
# Number of days in the months, in common years and leap years.
variable DaysInRomanMonthInCommonYear \
{ 31 28 31 30 31 30 31 31 30 31 30 31 }
variable DaysInRomanMonthInLeapYear \
{ 31 29 31 30 31 30 31 31 30 31 30 31 }
variable DaysInPriorMonthsInCommonYear [list 0]
variable DaysInPriorMonthsInLeapYear [list 0]
set i 0
foreach j $DaysInRomanMonthInCommonYear {
lappend DaysInPriorMonthsInCommonYear [incr i $j]
}
set i 0
foreach j $DaysInRomanMonthInLeapYear {
lappend DaysInPriorMonthsInLeapYear [incr i $j]
}
unset i j
# Julian day number of 0 January, 1 CE, in the proleptic Julian and
# Gregorian calendars.
variable JD0Jan1CEJul 1721423
variable JD0Jan1CEGreg 1721425
variable JD31Dec9999 5373484
# Posix epoch, expressed as seconds from the Julian epoch
variable PosixEpochAsJulianSeconds 210866803200
# Another epoch (Hi, Jeff!)
variable Roddenberry 1946
# Integer ranges
variable MINWIDE -9223372036854775808
variable MAXWIDE 9223372036854775807
# Day before Leap Day
variable FEB_28 58
# Conversion factors
variable DaysPer400Yr 146097; # Days per 400 year Gregorian cycle
variable DaysPerCentury 36524; # Days per common Gregorian century
variable DaysPer4Yr 1461; # Days per 4 year cycle
variable DaysPerYear 365; # Days per common year
variable DaysPerWeek 7;
variable SecondsPerDay 86400; # Seconds per day
variable SecondsPerHour 3600; # Seconds per hour
variable SecondsPerMinute 60; # Seconds per minute
variable MinutesPerHour 60; # Minutes per hour
variable HoursPerDay 24; # Hours per day
# Translation table to map Windows TZI onto cities, so that
# the Olson rules can apply. In some cases the mapping is ambiguous,
# so it's wise to specify $::env(TCL_TZ) rather than simply depending
# on the system time zone.
# The keys are long lists of values obtained from the time zone
# information in the Registry. In order, the list elements are:
# Bias StandardBias DaylightBias
# StandardDate.wYear StandardDate.wMonth StandardDate.wDayOfWeek
# StandardDate.wDay StandardDate.wHour StandardDate.wMinute
# StandardDate.wSecond StandardDate.wMilliseconds
# DaylightDate.wYear DaylightDate.wMonth DaylightDate.wDayOfWeek
# DaylightDate.wDay DaylightDate.wHour DaylightDate.wMinute
# DaylightDate.wSecond DaylightDate.wMilliseconds
# The values are the names of time zones where those rules apply.
# There is considerable ambiguity in certain zones; an attempt has
# been made to make a reasonable guess, but this table needs to be
# taken with a grain of salt.
variable WinZoneInfo [dict create \
{-43200 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Pacific/Kwajalein \
{-39600 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Pacific/Midway \
{-36000 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Pacific/Honolulu \
{-32400 0 3600 0 10 0 5 2 0 0 0 0 4 0 1 2 0 0 0} :America/Anchorage \
{-28800 0 3600 0 10 0 5 2 0 0 0 0 4 0 1 2 0 0 0} :America/Los_Angeles \
{-25200 0 3600 0 10 0 5 2 0 0 0 0 4 0 1 2 0 0 0} :America/Denver \
{-25200 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :America/Phoenix \
{-21600 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :America/Regina \
{-21600 0 3600 0 10 0 5 2 0 0 0 0 4 0 1 2 0 0 0} :America/Chicago \
{-18000 0 3600 0 10 0 5 2 0 0 0 0 4 0 1 2 0 0 0} :America/New_York \
{-18000 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :America/Indianapolis \
{-14400 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :America/Caracas \
{-14400 0 3600 0 3 6 2 0 0 0 0 0 10 6 2 0 0 0 0} :America/Santiago \
{-14400 0 3600 0 10 0 5 2 0 0 0 0 4 0 1 2 0 0 0} :America/Halifax \
{-12600 0 3600 0 10 0 5 2 0 0 0 0 4 0 1 2 0 0 0} :America/St_Johns \
{-10800 0 3600 0 2 0 2 2 0 0 0 0 10 0 3 2 0 0 0} :America/Sao_Paulo \
{-10800 0 3600 0 10 0 5 2 0 0 0 0 4 0 1 2 0 0 0} :America/Godthab \
{-10800 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :America/Buenos_Aires \
{-7200 0 3600 0 9 0 5 2 0 0 0 0 3 0 5 2 0 0 0} :America/Noronha \
{-3600 0 3600 0 10 0 5 3 0 0 0 0 3 0 5 2 0 0 0} :Atlantic/Azores \
{-3600 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Atlantic/Cape_Verde \
{0 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :UTC \
{0 0 3600 0 10 0 5 2 0 0 0 0 3 0 5 1 0 0 0} :Europe/London \
{3600 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Africa/Kinshasa \
{3600 0 3600 0 10 0 5 3 0 0 0 0 3 0 5 2 0 0 0} :CET \
{7200 0 3600 0 9 3 5 2 0 0 0 0 5 5 1 2 0 0 0} :Africa/Cairo \
{7200 0 3600 0 10 0 5 4 0 0 0 0 3 0 5 3 0 0 0} :Europe/Helsinki \
{7200 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Asia/Jerusalem \
{7200 0 3600 0 9 0 5 1 0 0 0 0 3 0 5 0 0 0 0} :Europe/Bucharest \
{7200 0 3600 0 10 0 5 3 0 0 0 0 3 0 5 2 0 0 0} :Europe/Athens \
{10800 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Asia/Riyadh \
{10800 0 3600 0 10 0 1 4 0 0 0 0 4 0 1 3 0 0 0} :Asia/Baghdad \
{10800 0 3600 0 10 0 5 3 0 0 0 0 3 0 5 2 0 0 0} :Europe/Moscow \
{12600 0 3600 0 9 2 4 2 0 0 0 0 3 0 1 2 0 0 0} :Asia/Tehran \
{14400 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Asia/Muscat \
{14400 0 3600 0 10 0 5 3 0 0 0 0 3 0 5 2 0 0 0} :Asia/Tbilisi \
{16200 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Asia/Kabul \
{18000 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Asia/Karachi \
{18000 0 3600 0 10 0 5 3 0 0 0 0 3 0 5 2 0 0 0} :Asia/Yekaterinburg \
{19800 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Asia/Calcutta \
{20700 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Asia/Katmandu \
{21600 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Asia/Dhaka \
{21600 0 3600 0 10 0 5 3 0 0 0 0 3 0 5 2 0 0 0} :Asia/Novosibirsk \
{23400 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Asia/Rangoon \
{25200 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Asia/Bangkok \
{25200 0 3600 0 10 0 5 3 0 0 0 0 3 0 5 2 0 0 0} :Asia/Krasnoyarsk \
{28800 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Asia/Chongqing \
{28800 0 3600 0 10 0 5 3 0 0 0 0 3 0 5 2 0 0 0} :Asia/Irkutsk \
{32400 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Asia/Tokyo \
{32400 0 3600 0 10 0 5 3 0 0 0 0 3 0 5 2 0 0 0} :Asia/Yakutsk \
{34200 0 3600 0 3 0 5 3 0 0 0 0 10 0 5 2 0 0 0} :Australia/Adelaide \
{34200 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Australia/Darwin \
{36000 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Australia/Brisbane \
{36000 0 3600 0 10 0 5 3 0 0 0 0 3 0 5 2 0 0 0} :Asia/Vladivostok \
{36000 0 3600 0 3 0 5 3 0 0 0 0 10 0 1 2 0 0 0} :Australia/Hobart \
{36000 0 3600 0 3 0 5 3 0 0 0 0 10 0 5 2 0 0 0} :Australia/Sydney \
{39600 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Pacific/Noumea \
{43200 0 3600 0 3 0 3 2 0 0 0 0 10 0 1 2 0 0 0} :Pacific/Auckland \
{43200 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Pacific/Fiji \
{46800 0 3600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} :Pacific/Tongatapu]
# Groups of fields that specify the date, priorities, and
# code bursts that determine Julian Day Number given those groups.
# The code in [clock scan] will choose the highest priority
# (lowest numbered) set of fields that determines the date.
variable DateParseActions {
{ seconds } 0 {}
{ julianDay } 1 {}
{ century yearOfCentury month dayOfMonth } 2 {
dict set date era CE
dict set date year [expr { 100 * [dict get $date century]
+ [dict get $date yearOfCentury] }]
set date [GetJulianDayFromEraYearMonthDay [K $date [set date {}]]]
}
{ century yearOfCentury dayOfYear } 2 {
dict set date era CE
dict set date year [expr { 100 * [dict get $date century]
+ [dict get $date yearOfCentury] }]
set date [GetJulianDayFromEraYearDay [K $date [set date {}]]]
}
{ iso8601Century iso8601YearOfCentury iso8601Week dayOfWeek } 2 {
dict set date era CE
dict set date iso8601Year \
[expr { 100 * [dict get $date iso8601Century]
+ [dict get $date iso8601YearOfCentury] }]
set date [GetJulianDayFromEraYearWeekDay [K $date [set date {}]]]
}
{ yearOfCentury month dayOfMonth } 3 {
set date [InterpretTwoDigitYear [K $date [set date {}]] $baseTime]
dict set date era CE
set date [GetJulianDayFromEraYearMonthDay [K $date [set date {}]]]
}
{ yearOfCentury dayOfYear } 3 {
set date [InterpretTwoDigitYear [K $date [set date {}]] $baseTime]
dict set date era CE
set date [GetJulianDayFromEraYearDay [K $date [set date {}]]]
}
{ iso8601YearOfCentury iso8601Week dayOfWeek } 3 {
set date [InterpretTwoDigitYear \
[K $date [set date {}]] $baseTime \
iso8601YearOfCentury iso8601Year]
dict set date era CE
set date [GetJulianDayFromEraYearWeekDay [K $date [set date {}]]]
}
{ month dayOfMonth } 4 {
set date [AssignBaseYear [K $date [set date {}]] \
$baseTime $timeZone]
set date [GetJulianDayFromEraYearMonthDay [K $date [set date {}]]]
}
{ dayOfYear } 4 {
set date [AssignBaseYear [K $date [set date {}]] \
$baseTime $timeZone]
set date [GetJulianDayFromEraYearDay [K $date [set date {}]]]
}
{ iso8601Week dayOfWeek } 4 {
set date [AssignBaseIso8601Year [K $date [set date {}]] \
$baseTime $timeZone]
set date [GetJulianDayFromEraYearWeekDay [K $date [set date {}]]]
}
{ dayOfMonth } 5 {
set date [AssignBaseMonth [K $date [set date {}]] \
$baseTime $timeZone]
set date [GetJulianDayFromEraYearMonthDay [K $date [set date {}]]]
}
{ dayOfWeek } 6 {
set date [AssignBaseWeek [K $date [set date {}]] \
$baseTime $timeZone]
set date [GetJulianDayFromEraYearWeekDay [K $date [set date {}]]]
}
{} 7 {
set date [AssignBaseJulianDay [K $date [set date {}]] \
$baseTime $timeZone]
}
}
# Groups of fields that specify time of day, priorities,
# and code that processes them
variable TimeParseActions {
seconds 1 {}
{ hourAMPM minute second amPmIndicator } 2 {
dict set date secondOfDay [InterpretHMSP $date]
}
{ hour minute second } 2 {
dict set date secondOfDay [InterpretHMS $date]
}
{ hourAMPM minute amPmIndicator } 3 {
dict set date second 0
dict set date secondOfDay [InterpretHMSP $date]
}
{ hour minute } 3 {
dict set date second 0
dict set date secondOfDay [InterpretHMS $date]
}
{ hourAMPM amPmIndicator } 4 {
dict set date minute 0
dict set date second 0
dict set date secondOfDay [InterpretHMSP $date]
}
{ hour } 4 {
dict set date minute 0
dict set date second 0
dict set date secondOfDay [InterpretHMS $date]
}
{ } 5 {
dict set date secondOfDay 0
}
}
# Legacy time zones, used primarily for parsing RFC822 dates.
variable LegacyTimeZone [dict create \
gmt +0000 \
ut +0000 \
utc +0000 \
bst +0100 \
wet +0000 \
wat -0100 \
at -0200 \
nft -0330 \
nst -0330 \
ndt -0230 \
ast -0400 \
adt -0300 \
est -0500 \
edt -0400 \
cst -0600 \
cdt -0500 \
mst -0700 \
mdt -0600 \
pst -0800 \
pdt -0700 \
yst -0900 \
ydt -0800 \
hst -1000 \
hdt -0900 \
cat -1000 \
ahst -1000 \
nt -1100 \
idlw -1200 \
cet +0100 \
cest +0200 \
met +0100 \
mewt +0100 \
mest +0200 \
swt +0100 \
sst +0200 \
fwt +0100 \
fst +0200 \
eet +0200 \
eest +0300 \
bt +0300 \
it +0330 \
zp4 +0400 \
zp5 +0500 \
ist +0530 \
zp6 +0600 \
wast +0700 \
wadt +0800 \
jt +0730 \
cct +0800 \
jst +0900 \
cast +0930 \
cadt +1030 \
east +1000 \
eadt +1030 \
gst +1000 \
nzt +1200 \
nzst +1200 \
nzdt +1300 \
idle +1200 \
a +0100 \
b +0200 \
c +0300 \
d +0400 \
e +0500 \
f +0600 \
g +0700 \
h +0800 \
i +0900 \
k +1000 \
l +1100 \
m +1200 \
n -0100 \
o -0200 \
p -0300 \
q -0400 \
r -0500 \
s -0600 \
t -0700 \
u -0800 \
v -0900 \
w -1000 \
x -1100 \
y -1200 \
z +0000 \
]
# Caches
variable LocaleNumeralCache {}; # Dictionary whose keys are locale
# names and whose values are pairs
# comprising regexes matching numerals
# in the given locales and dictionaries
# mapping the numerals to their numeric
# values.
variable McLoaded {}; # Dictionary whose keys are locales
# in which [mcload] has been executed
# and whose values are immaterial
# variable CachedSystemTimeZone; # If 'CachedSystemTimeZone' exists,
# it contains the value of the
# system time zone, as determined from
# the environment.
variable TZData; # Array whose keys are time zone names
# and whose values are lists of quads
# comprising start time, UTC offset,
# Daylight Saving Time indicator, and
# time zone abbreviation.
}
#----------------------------------------------------------------------
#
# K --
#
# The K combinator returns its first argument. It's used for
# reference count management.
#
# Parameters:
# x - Argument to be unreferenced.
# y - Unused.
#
# Results:
# Returns the first argument.
#
# Side effects:
# None.
#
# The K combinator is used for its effect that [K $x [set x {}]]
# reads out the value of x destructively, giving an unshared Tcl
# object and avoiding 'copy on write'
#
#----------------------------------------------------------------------
proc ::tcl::clock::K { x y } { return $x }
#----------------------------------------------------------------------
#
# clock format --
#
# Formats a count of seconds since the Posix Epoch as a time
# of day.
#
# The 'clock format' command formats times of day for output.
# Refer to the user documentation to see what it does.
#
#----------------------------------------------------------------------
proc ::tcl::clock::format { args } {
variable SecondsPerDay
variable SecondsPerHour
variable SecondsPerMinute
variable MinutesPerHour
variable HoursPerDay
variable DaysPerYear
variable DaysPerWeek
set format {}
# Check the count of args
if { [llength $args] < 1 || [llength $args] % 2 != 1 } {
return -code error \
-errorcode [list CLOCK wrongNumArgs] \
"wrong \# args: should be\
\"[lindex [info level 0] 0] clockval\
?-format string? ?-gmt boolean?\
?-locale LOCALE? ?-timezone ZONE?\""
}
# Set defaults
set clockval [lindex $args 0]
set format {%a %b %d %H:%M:%S %z %Y}
set gmt 0
set locale C
set timezone [GetSystemTimeZone]
# Pick up command line options.
foreach { flag value } [lreplace $args 0 0] {
set saw($flag) {}
switch -exact -- $flag {
-format {
set format $value
}
-gmt {
set gmt $value
}
-locale {
set locale $value
}
-timezone {
set timezone $value
}
default {
return -code error \
-errorcode [list CLOCK badSwitch $flag] \
"bad switch \"$flag\",\
must be -format, -gmt, -locale or -timezone"
}
}
}
# Check options for validity
if { [info exists saw(-gmt)] && [info exists saw(-timezone)] } {
return -code error \
-errorcode [list CLOCK gmtWithTimezone] \
"cannot use -gmt and -timezone in same call"
}
if { [catch { expr { wide($clockval) } } result] } {
return -code error \
"expected integer but got \"$clockval\""
}
if { ![string is boolean $gmt] } {
return -code error \
"expected boolean value but got \"$gmt\""
} else {
if { $gmt } {
set timezone :GMT
}
}
EnterLocale $locale oldLocale
# Change locale if a fresh locale has been given on the command line.
set status [catch {
# Map away the locale-dependent composite format groups
set format [LocalizeFormat $format]
# Convert the given time to local time.
set date [dict create seconds $clockval]
set date [ConvertUTCToLocal [K $date [set date {}]] $timezone]
# Extract the fields of the date.
set date [GetJulianDay [K $date [set date {}]]]
set date [GetGregorianEraYearDay [K $date [set date {}]]]
set date [GetMonthDay [K $date [set date {}]]]
set date [GetYearWeekDay [K $date [set date {}]]]
# Format the result
set state {}
set retval {}
foreach char [split $format {}] {
switch -exact $state {
{} {
if { [string equal % $char] } {
set state percent
} else {
append retval $char
}
}
percent { # Character following a '%' character
set state {}
switch -exact -- $char {
% { # A literal character, '%'
append retval %
}
a { # Day of week, abbreviated
set dow [expr { [dict get $date dayOfWeek] % 7 }]
append retval \
[lindex [mc DAYS_OF_WEEK_ABBREV] $dow]
}
A { # Day of week, spelt out.
set dow [expr { [dict get $date dayOfWeek] % 7 }]
append retval [lindex [mc DAYS_OF_WEEK_FULL] $dow]
}
b - h { # Name of month, abbreviated.
set month [expr { [dict get $date month] - 1 }]
append retval [lindex [mc MONTHS_ABBREV] $month]
}
B { # Name of month, spelt out
set month [expr { [dict get $date month] - 1 }]
append retval [lindex [mc MONTHS_FULL] $month]
}
C { # Century number
set cent [expr { [dict get $date year] / 100 }]
append retval [::format %02d $cent]
}
d { # Day of month, with leading zero
append retval [::format %02d \
[dict get $date dayOfMonth]]
}
e { # Day of month, without leading zero
append retval [::format %2d \
[dict get $date dayOfMonth]]
}
E { # Format group in a locale-dependent
# alternative era
set state percentE
if { ![dict exists $date localeEra] } {
set date [GetLocaleEra [K $date [set date {}]]]
}
}
g { # Two-digit year relative to ISO8601
# week number
set year \
[expr { [dict get $date iso8601Year] % 100 }]
append retval [::format %02d $year]
}
G { # Four-digit year relative to ISO8601
# week number
append retval [::format %04d \
[dict get $date iso8601Year]]
}
H { # Hour in the 24-hour day, leading zero
append retval \
[::format %02d \
[expr { [dict get $date localSeconds]
/ $SecondsPerHour
% $HoursPerDay }]]
}
I { # Hour AM/PM, with leading zero
set hour12 \
[expr { ( ( ( [dict get $date localSeconds]
% $SecondsPerDay )
+ $SecondsPerDay
- $SecondsPerHour )
/ $SecondsPerHour )
% 12 + 1 }]
append retval [::format %02d $hour12]
}
j { # Day of year (001-366)
append retval [::format %03d \
[dict get $date dayOfYear]]
}
J { # Julian Day Number
append retval [::format %07ld \
[dict get $date julianDay]]
}
k { # Hour (0-23), no leading zero
append retval \
[::format %2d \
[expr { [dict get $date localSeconds]
/ $SecondsPerHour
% $HoursPerDay }]]
}
l { # Hour (12-11), no leading zero
set hour12 \
[expr { ( ( ( [dict get $date localSeconds]
% $SecondsPerDay )
+ $SecondsPerDay
- $SecondsPerHour )
/ $SecondsPerHour )
% 12 + 1 }]
append retval [::format %2d $hour12]
}
m { # Month number, leading zero
append retval [::format %02d \
[dict get $date month]]
}
M { # Minute of the hour, leading zero
append retval \
[::format %02d \
[expr { [dict get $date localSeconds]
/ $SecondsPerMinute
% $MinutesPerHour }]]
}
n { # A literal newline
append retval \n
}
N { # Month number, no leading zero
append retval [::format %2d \
[dict get $date month]]
}
O { # A format group in the locale's
# alternative numerals
set state percentO
}
p { # Localized 'AM' or 'PM' indicator
# converted to uppercase
set tod [expr { [dict get $date localSeconds]
% $SecondsPerDay }]
if { $tod >= ( $SecondsPerDay / 2 ) } {
append retval [string toupper [mc PM]]
} else {
append retval [string toupper [mc AM]]
}
}
P { # Localized 'AM' or 'PM' indicator
set tod [expr { [dict get $date localSeconds]
% $SecondsPerDay }]
if { $tod >= ( $SecondsPerDay / 2 ) } {
append retval [mc PM]
} else {
append retval [mc AM]
}
}
Q { # Hi, Jeff!
append retval [FormatStarDate $date]
}
s { # Seconds from the Posix Epoch
append retval $clockval
}
S { # Second of the minute, with
# leading zero
append retval \
[::format %02d \
[expr { [dict get $date localSeconds]
% $SecondsPerMinute }]]
}
t { # A literal tab character
append retval \t
}
u { # Day of the week (1-Monday, 7-Sunday)
append retval [dict get $date dayOfWeek]
}
U { # Week of the year (00-53). The
# first Sunday of the year is the
# first day of week 01
set dow [dict get $date dayOfWeek]
if { $dow == 7 } {
set dow 0
}
incr dow
set weekNumber \
[expr { ( [dict get $date dayOfYear]
- $dow
+ $DaysPerWeek )
/ $DaysPerWeek }]
append retval [::format %02d $weekNumber]
}
V { # The ISO8601 week number
append retval [::format %02d \
[dict get $date iso8601Week]]
}
w { # Day of the week (0-Sunday,
# 6-Saturday)
append retval \
[expr { [dict get $date dayOfWeek] % 7 }]
}
W { # Week of the year (00-53). The first
# Monday of the year is the first day
# of week 01.
set weekNumber \
[expr { ( [dict get $date dayOfYear]
- [dict get $date dayOfWeek]
+ $DaysPerWeek )
/ $DaysPerWeek }]
append retval [::format %02d $weekNumber]
}
y { # The two-digit year of the century
append retval \
[::format %02d \
[expr { [dict get $date year] % 100 }]]
}
Y { # The four-digit year
append retval [::format %04d \
[dict get $date year]]
}
z { # The time zone as hours and minutes
# east (+) or west (-) of Greenwich
set z [dict get $date tzOffset]
if { $z < 0 } {
set z [expr { - $z }]
append retval -
} else {
append retval +
}
append retval [::format %02d \
[expr { $z / $SecondsPerHour }]]
set z [expr { $z % $SecondsPerHour }]
append retval \
[::format %02d \
[expr { $z / $SecondsPerMinute }]]
set z [expr { $z % $SecondsPerMinute }]
if { $z != 0 } {
append retval [::format %02d $z]
}
}
Z { # The name of the time zone
append retval [dict get $date tzName]
}
% { # A literal percent character
append retval %
}
default { # An unknown escape sequence
append retval % $char
}
}
}
percentE { # Character following %E
set state {}
switch -exact -- $char {
C { # Locale-dependent era
append retval [dict get $date localeEra]
}
y { # Locale-dependent year of the era
set y [dict get $date localeYear]
if { $y >= 0 && $y < 100 } {
append retval [lindex [mc LOCALE_NUMERALS] $y]
} else {
append retval $y
}
}
default { # Unknown format group
append retval %E $char
}
}
}
percentO { # Character following %O
set state {}
switch -exact -- $char {
d - e { # Day of the month in alternative
# numerals
append retval [lindex \
[mc LOCALE_NUMERALS] \
[dict get $date dayOfMonth]]
}
H - k { # Hour of the day in alternative
# numerals
set hour [expr { [dict get $date localSeconds]
/ $SecondsPerHour
% $HoursPerDay }]
append retval [lindex [mc LOCALE_NUMERALS] $hour]
}
I - l { # Hour (12-11) AM/PM in alternative
# numerals
set hour12 \
[expr { ( ( ( [dict get $date localSeconds]
% $SecondsPerDay )
+ $SecondsPerDay
- $SecondsPerHour )
/ $SecondsPerHour )
% 12 + 1 }]
append retval [lindex [mc LOCALE_NUMERALS] $hour12]
}
m { # Month number in alternative numerals
append retval [lindex \
[mc LOCALE_NUMERALS] \
[dict get $date month]]
}
M { # Minute of the hour in alternative
# numerals
set minute [expr { [dict get $date localSeconds]
/ $SecondsPerMinute
% $MinutesPerHour }]
append retval [lindex [mc LOCALE_NUMERALS] $minute]
}
S { # Second of the minute in alternative
# numerals
set second [expr { [dict get $date localSeconds]
% $SecondsPerMinute }]
append retval [lindex [mc LOCALE_NUMERALS] $second]
}
u { # Day of the week (Monday=1,Sunday=7)
# in alternative numerals
append retval [lindex \
[mc LOCALE_NUMERALS] \
[dict get $date dayOfWeek]]
}
w { # Day of the week (Sunday=0,Saturday=6)
# in alternative numerals
append retval \
[lindex \
[mc LOCALE_NUMERALS] \
[expr { [dict get $date dayOfWeek] % 7 }]]
}
y { # Year of the century in alternative
# numerals
append retval \
[lindex \
[mc LOCALE_NUMERALS] \
[expr { [dict get $date year] % 100 }]]
}
default { # Unknown format group
append retval %O $char
}
}
}
}
}
# Clean up any improperly terminated groups
switch -exact -- $state {
percent {
append retval %
}
percentE {
append retval %E
}
percentO {
append retval %O
}
}
set retval
} result]
# Restore the locale
if { [info exists oldLocale] } {
mclocale $oldLocale
}
if { $status == 1 } {
if { [lindex $::errorCode 0] eq {clock} } {
return -code error $result
} else {
return -code error \
-errorcode $::errorCode -errorinfo $::errorInfo \
$result
}
} else {
return $result
}
}
#----------------------------------------------------------------------
#
# clock scan --
#
# Inputs a count of seconds since the Posix Epoch as a time
# of day.
#
# The 'clock format' command scans times of day on input.
# Refer to the user documentation to see what it does.
#
#----------------------------------------------------------------------
proc ::tcl::clock::scan { args } {
set format {}
# Check the count of args
if { [llength $args] < 1 || [llength $args] % 2 != 1 } {
return -code error \
-errorcode [list CLOCK wrongNumArgs] \
"wrong \# args: should be\
\"[lindex [info level 0] 0] string\
?-base seconds?\
?-format string? ?-gmt boolean?\
?-locale LOCALE? ?-timezone ZONE?\""
}
# Set defaults
set base [clock seconds]
set string [lindex $args 0]
set format {}
set gmt 0
set locale C
set timezone [GetSystemTimeZone]
# Pick up command line options.
foreach { flag value } [lreplace $args 0 0] {
set saw($flag) {}
switch -exact -- $flag {
-base {
set base $value
}
-format {
set format $value
}
-gmt {
set gmt $value
}
-locale {
set locale $value
}
-timezone {
set timezone $value
}
default {
return -code error \
-errorcode [list CLOCK badSwitch $flag] \
"bad switch \"$flag\",\
must be -base, -format, -gmt, -locale or -timezone"
}
}
}
# Check options for validity
if { [info exists saw(-gmt)] && [info exists saw(-timezone)] } {
return -code error \
-errorcode [list CLOCK gmtWithTimezone] \
"cannot use -gmt and -timezone in same call"
}
if { [catch { expr { wide($base) } } result] } {
return -code error \
"expected integer but got \"$base\""
}
if { ![string is boolean $gmt] } {
return -code error \
"expected boolean value but got \"$gmt\""
} else {
if { $gmt } {
set timezone :GMT
}
}
if { ![info exists saw(-format)] } {
if { [info exists saw(-timezone)] || [info exists saw(-locale)] } {
return -code error \
-errorcode [list CLOCK flagWithLegacyFormat] \
"legacy \[clock scan\] does not support -timezone or\
-locale"
}
if { [catch {
Oldscan $string -base $base -gmt $gmt
} retval] } {
return -code error \
-errorcode $::errorCode -errorinfo $::errorInfo \
$retval
} else {
return $retval
}
}
# Change locale if a fresh locale has been given on the command line.
EnterLocale $locale oldLocale
set status [catch {
# Map away the locale-dependent composite format groups
set format [LocalizeFormat $format]
set scanner [ParseClockScanFormat $format]
$scanner $string $base $timezone
} result]
# Restore the locale
if { [info exists oldLocale] } {
mclocale $oldLocale
}
if { $status == 1 } {
if { [lindex $::errorCode 0] eq {clock} } {
return -code error $result
} else {
return -code error \
-errorcode $::errorCode -errorinfo $::errorInfo \
$result
}
} else {
return $result
}
}
#----------------------------------------------------------------------
#
# ParseClockScanFormat --
#
# Parses a format string given to [clock scan -format]
#
# Parameters:
# None.
#
# Results:
# Constructs and returns a procedure that accepts the
# string being scanned, the base time, and the time zone.
# The procedure will either return the scanned time or
# else throw an error that should be rethrown to the caller
# of [clock scan]
#
# Side effects:
# The given procedure is defined in the ::tcl::clock
# namespace. Scan procedures are not deleted once installed.
#
# Why do we parse dates by defining a procedure to parse them?
# The reason is that by doing so, we have one convenient place to
# cache all the information: the regular expressions that match the
# patterns (which will be compiled), the code that assembles the
# date information, everything lands in one place. In this way,
# when a given format is reused at run time, all the information
# of how to apply it is available in a single place.
#
#----------------------------------------------------------------------
proc ::tcl::clock::ParseClockScanFormat { formatString } {
variable DateParseActions
variable TimeParseActions
# Condense whitespace
regsub -all {[[:space:]]+} $formatString { } formatString
# Check whether the format has been parsed previously, and return
# the existing recognizer if it has.
set procName [namespace current]::scanproc'$formatString'[mclocale]
if { [info procs $procName] != {} } {
return $procName
}
# Walk through the groups of the format string. In this loop, we
# accumulate:
# - a regular expression that matches the string,
# - the count of capturing brackets in the regexp
# - a set of code that post-processes the fields captured by the regexp,
# - a dictionary whose keys are the names of fields that are present
# in the format string.
set re {^[[:space:]]*}
set captureCount 0
set postcode {}
set fieldSet [dict create]
set fieldCount 0
set postSep {}
set state {}
foreach c [split $formatString {}] {
switch -exact -- $state {
{} {
if { $c eq "%" } {
set state %
} elseif { $c eq " " } {
append re {[[:space:]]+}
} else {
if { ! [string is alnum $c] } {
append re \\
}
append re $c
}
}
% {
set state {}
switch -exact -- $c {
% {
append re %
}
{ } {
append re "\[\[:space:\]\]*"
}
a - A { # Day of week, in words
set l {}
foreach \
i {7 1 2 3 4 5 6} \
abr [mc DAYS_OF_WEEK_ABBREV] \
full [mc DAYS_OF_WEEK_FULL] {
dict set l $abr $i
dict set l $full $i
incr i
}
foreach { regex lookup } [UniquePrefixRegexp $l] break
append re ( $regex )
dict set fieldSet dayOfWeek [incr fieldCount]
append postcode "dict set date dayOfWeek \[" \
"dict get " [list $lookup] " \$field" \
[incr captureCount] \
"\]\n"
}
b - B - h { # Name of month
set i 0
set l {}
foreach \
abr [mc MONTHS_ABBREV] \
full [mc MONTHS_FULL] {
incr i
dict set l $abr $i
dict set l $full $i
}
foreach { regex lookup } [UniquePrefixRegexp $l] break
append re ( $regex )
dict set fieldSet month [incr fieldCount]
append postcode "dict set date month \[" \
"dict get " [list $lookup] " \$field" \
[incr captureCount] \
"\]\n"
}
C { # Gregorian century
append re \\s*(\\d\\d?)
dict set fieldSet century [incr fieldCount]
append postcode "dict set date century \[" \
"::scan \$field" [incr captureCount] " %d" \
"\]\n"
}
d - e { # Day of month
append re \\s*(\\d\\d?)
dict set fieldSet dayOfMonth [incr fieldCount]
append postcode "dict set date dayOfMonth \[" \
"::scan \$field" [incr captureCount] " %d" \
"\]\n"
}
E { # Prefix for locale-specific codes
set state %E
}
g { # ISO8601 2-digit year
append re \\s*(\\d\\d)
dict set fieldSet iso8601YearOfCentury \
[incr fieldCount]
append postcode \
"dict set date iso8601YearOfCentury \[" \
"::scan \$field" [incr captureCount] " %d" \
"\]\n"
}
G { # ISO8601 4-digit year
append re \\s*(\\d\\d)(\\d\\d)
dict set fieldSet iso8601Century [incr fieldCount]
dict set fieldSet iso8601YearOfCentury \
[incr fieldCount]
append postcode \
"dict set date iso8601Century \[" \
"::scan \$field" [incr captureCount] " %d" \
"\]\n" \
"dict set date iso8601YearOfCentury \[" \
"::scan \$field" [incr captureCount] " %d" \
"\]\n"
}
H - k { # Hour of day
append re \\s*(\\d\\d?)
dict set fieldSet hour [incr fieldCount]
append postcode "dict set date hour \[" \
"::scan \$field" [incr captureCount] " %d" \
"\]\n"
}
I - l { # Hour, AM/PM
append re \\s*(\\d\\d?)
dict set fieldSet hourAMPM [incr fieldCount]
append postcode "dict set date hourAMPM \[" \
"::scan \$field" [incr captureCount] " %d" \
"\]\n"
}
j { # Day of year
append re \\s*(\\d\\d?\\d?)
dict set fieldSet dayOfYear [incr fieldCount]
append postcode "dict set date dayOfYear \[" \
"::scan \$field" [incr captureCount] " %d" \
"\]\n"
}
J { # Julian Day Number
append re \\s*(\\d+)
dict set fieldSet julianDay [incr fieldCount]
append postcode "dict set date julianDay \[" \
"::scan \$field" [incr captureCount] " %ld" \
"\]\n"
}
m - N { # Month number
append re \\s*(\\d\\d?)
dict set fieldSet month [incr fieldCount]
append postcode "dict set date month \[" \
"::scan \$field" [incr captureCount] " %d" \
"\]\n"
}
M { # Minute
append re \\s*(\\d\\d?)
dict set fieldSet minute [incr fieldCount]
append postcode "dict set date minute \[" \
"::scan \$field" [incr captureCount] " %d" \
"\]\n"
}
n { # Literal newline
append re \\n
}
O { # Prefix for locale numerics
set state %O
}
p - P { # AM/PM indicator
set l [list [mc AM] 0 [mc PM] 1]
foreach { regex lookup } [UniquePrefixRegexp $l] break
append re ( $regex )
dict set fieldSet amPmIndicator [incr fieldCount]
append postcode "dict set date amPmIndicator \[" \
"dict get " [list $lookup] " \[string tolower " \
"\$field" \
[incr captureCount] \
"\]\]\n"
}
Q { # Hi, Jeff!
append re {Stardate\s+([-+]?\d+)(\d\d\d)[.](\d)}
incr captureCount
dict set fieldSet seconds [incr fieldCount]
append postcode {dict set date seconds } \[ \
{ParseStarDate $field} [incr captureCount] \
{ $field} [incr captureCount] \
{ $field} [incr captureCount] \
\] \n
}
s { # Seconds from Posix Epoch
# This next case is insanely difficult,
# because it's problematic to determine
# whether the field is actually within
# the range of a wide integer.
append re {\s*([-+]?\d+)}
dict set fieldSet seconds [incr fieldCount]
append postcode {dict set date seconds } \[ \
{ScanWide $field} [incr captureCount] \] \n
}
S { # Second
append re \\s*(\\d\\d?)
dict set fieldSet second [incr fieldCount]
append postcode "dict set date second \[" \
"::scan \$field" [incr captureCount] " %d" \
"\]\n"
}
t { # Literal tab character
append re \\t
}
u - w { # Day number within week, 0 or 7 == Sun
# 1=Mon, 6=Sat
append re \\s*(\\d)
dict set fieldSet dayOfWeek [incr fieldCount]
append postcode {::scan $field} [incr captureCount] \
{ %d dow} \n \
{
if { $dow == 0 } {
set dow 7
} elseif { $dow > 7 } {
return -code error \
-errorcode [list CLOCK badDayOfWeek] \
"day of week is greater than 7"
}
dict set date dayOfWeek $dow
}
}
U { # Week of year. The
# first Sunday of the year is the
# first day of week 01. No scan rule
# uses this group.
append re \\s*\\d\\d?
}
V { # Week of ISO8601 year
append re \\s*(\\d\\d?)
dict set fieldSet iso8601Week [incr fieldCount]
append postcode "dict set date iso8601Week \[" \
"::scan \$field" [incr captureCount] " %d" \
"\]\n"
}
W { # Week of the year (00-53). The first
# Monday of the year is the first day
# of week 01. No scan rule uses this
# group.
append re \\s*\\d\\d?
}
y { # Two-digit Gregorian year
append re \\s*(\\d\\d?)
dict set fieldSet yearOfCentury [incr fieldCount]
append postcode "dict set date yearOfCentury \[" \
"::scan \$field" [incr captureCount] " %d" \
"\]\n"
}
Y { # 4-digit Gregorian year
append re \\s*(\\d\\d)(\\d\\d)
dict set fieldSet century [incr fieldCount]
dict set fieldSet yearOfCentury [incr fieldCount]
append postcode \
"dict set date century \[" \
"::scan \$field" [incr captureCount] " %d" \
"\]\n" \
"dict set date yearOfCentury \[" \
"::scan \$field" [incr captureCount] " %d" \
"\]\n"
}
z - Z { # Time zone name
append re {(?:([-+]\d\d:?\d\d(?::?\d\d)?)|([[:alnum:]]{1,4}))}
dict set fieldSet tzName [incr fieldCount]
append postcode \
{if } \{ { $field} [incr captureCount] \
{ ne "" } \} { } \{ \n \
{dict set date tzName $field} \
$captureCount \n \
\} { else } \{ \n \
{dict set date tzName } \[ \
{ConvertLegacyTimeZone $field} \
[incr captureCount] \] \n \
\} \n \
}
% { # Literal percent character
append re %
}
default {
append re %
if { ! [string is alnum $c] } {
append re \\
}
append re $c
}
}
}
%E {
switch -exact -- $c {
C { # Locale-dependent era
set d {}
foreach triple [mc LOCALE_ERAS] {
foreach {t symbol year} $triple break
dict set d $symbol $year
}
foreach { regex lookup } [UniquePrefixRegexp $d] break
append re (?: $regex )
}
y { # Locale-dependent year of the era
foreach {regex lookup} [LocaleNumeralMatcher] break
append re $regex
incr fieldCount
}
default {
append re %E
if { ! [string is alnum $c] } {
append re \\
}
append re $c
}
}
set state {}
}
%O {
switch -exact -- $c {
d - e {
foreach {regex lookup} [LocaleNumeralMatcher] break
append re $regex
dict set fieldSet dayOfMonth [incr fieldCount]
append postcode "dict set date dayOfMonth \[" \
"dict get " [list $lookup] " \$field" \
[incr captureCount] \
"\]\n"
}
H - k {
foreach {regex lookup} [LocaleNumeralMatcher] break
append re $regex
dict set fieldSet hour [incr fieldCount]
append postcode "dict set date hour \[" \
"dict get " [list $lookup] " \$field" \
[incr captureCount] \
"\]\n"
}
I - l {
foreach {regex lookup} [LocaleNumeralMatcher] break
append re $regex
dict set fieldSet hourAMPM [incr fieldCount]
append postcode "dict set date hourAMPM \[" \
"dict get " [list $lookup] " \$field" \
[incr captureCount] \
"\]\n"
}
m {
foreach {regex lookup} [LocaleNumeralMatcher] break
append re $regex
dict set fieldSet month [incr fieldCount]
append postcode "dict set date month \[" \
"dict get " [list $lookup] " \$field" \
[incr captureCount] \
"\]\n"
}
M {
foreach {regex lookup} [LocaleNumeralMatcher] break
append re $regex
dict set fieldSet minute [incr fieldCount]
append postcode "dict set date minute \[" \
"dict get " [list $lookup] " \$field" \
[incr captureCount] \
"\]\n"
}
S {
foreach {regex lookup} [LocaleNumeralMatcher] break
append re $regex
dict set fieldSet second [incr fieldCount]
append postcode "dict set date second \[" \
"dict get " [list $lookup] " \$field" \
[incr captureCount] \
"\]\n"
}
u - w {
foreach {regex lookup} [LocaleNumeralMatcher] break
append re $regex
dict set fieldSet dayOfWeek [incr fieldCount]
append postcode "set dow \[dict get " [list $lookup] \
{ $field} [incr captureCount] \] \n \
{
if { $dow == 0 } {
set dow 7
} elseif { $dow > 7 } {
return -code error \
-errorcode [list CLOCK badDayOfWeek] \
"day of week is greater than 7"
}
dict set date dayOfWeek $dow
}
}
y {
foreach {regex lookup} [LocaleNumeralMatcher] break
append re $regex
dict set fieldSet yearOfCentury [incr fieldCount]
append postcode {dict set date yearOfCentury } \[ \
{dict get } [list $lookup] { $field} \
[incr captureCount] \] \n
}
default {
append re %O
if { ! [string is alnum $c] } {
append re \\
}
append re $c
}
}
set state {}
}
}
}
# Clean up any unfinished format groups
append re $state \\s*\$
# Build the procedure
set procBody \n
append procBody "if \{ !\[ regexp -nocase [list $re] \$string ->"
for { set i 1 } { $i <= $captureCount } { incr i } {
append procBody " " field $i
}
append procBody "\] \} \{" \n
append procBody {
return -code error -errorcode [list CLOCK badInputString] \
{input string does not match supplied format}
}
append procBody \}\n
append procBody "set date \[dict create\]" \n
append procBody {dict set date tzName $timeZone} \n
append procBody $postcode
# Add code that gets Julian Day Number from the fields.
append procBody [MakeParseCodeFromFields $fieldSet $DateParseActions]
# Get time of day
append procBody [MakeParseCodeFromFields $fieldSet $TimeParseActions]
# Assemble seconds, and convert local nominal time to UTC.
if { ![dict exists $fieldSet seconds]
&& ![dict exists $fieldSet starDate] } {
append procBody {
if { [dict get $date julianDay] > $::tcl::clock::JD31Dec9999 } {
return -code error -errorcode [list CLOCK dateTooLarge] \
"requested date too large to represent"
}
dict set date localSeconds \
[expr { -$::tcl::clock::PosixEpochAsJulianSeconds
+ ( $::tcl::clock::SecondsPerDay
* wide([dict get $date julianDay]) )
+ [dict get $date secondOfDay] }]
}
}
if { ![dict exists $fieldSet seconds]
&& ![dict exists $fieldSet starDate] } {
append procBody {
set date [::tcl::clock::ConvertLocalToUTC [K $date [set date {}]]]
}
}
# Return result
append procBody {return [dict get $date seconds]} \n
proc $procName { string baseTime timeZone } $procBody
# puts [list proc $procName [list string baseTime timeZone] $procBody]
return $procName
}
#----------------------------------------------------------------------
#
# LocaleNumeralMatcher --
#
# Composes a regexp that captures the numerals in the given
# locale, and a dictionary to map them to conventional numerals.
#
# Parameters:
# none.
#
# Results:
# Returns a two-element list comprising the regexp and the
# dictionary.
#
# Side effects:
# Caches the result.
#
#----------------------------------------------------------------------
proc ::tcl::clock::LocaleNumeralMatcher {} {
variable LocaleNumeralCache
set l [mclocale]
if { ![dict exists $LocaleNumeralCache $l] } {
set d {}
set i 0
set sep \(
foreach n [mc LOCALE_NUMERALS] {
dict set d $n $i
regsub -all {[^[:alnum:]]} $n \\\\& subex
append re $sep $subex
set sep |
incr i
}
append re \)
dict set LocaleNumeralCache $l [list $re $d]
}
return [dict get $LocaleNumeralCache $l]
}
#----------------------------------------------------------------------
#
# UniquePrefixRegexp --
#
# Composes a regexp that performs unique-prefix matching. The
# RE matches one of a supplied set of strings, or any unique
# prefix thereof.
#
# Parameters:
# data - List of alternating match-strings and values.
# Match-strings with distinct values are considered
# distinct.
#
# Results:
# Returns a two-element list. The first is a regexp that
# matches any unique prefix of any of the strings. The second
# is a dictionary whose keys are match values from the regexp
# and whose values are the corresponding values from 'data'.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::UniquePrefixRegexp { data } {
# The 'successors' dictionary will contain, for each string that
# is a prefix of any key, all characters that may follow that
# prefix. The 'prefixMapping' dictionary will have keys that
# are prefixes of keys and values that correspond to the keys.
set prefixMapping [dict create]
set successors [dict create {} {}]
# Walk the key-value pairs
foreach { key value } $data {
# Construct all prefixes of the key;
set prefix {}
foreach char [split $key {}] {
set oldPrefix $prefix
dict set successors $oldPrefix $char {}
append prefix $char
# Put the prefixes in the 'prefixMapping' and 'successors'
# dictionaries
dict lappend prefixMapping $prefix $value
if { ![dict exists $successors $prefix] } {
dict set successors $prefix {}
}
}
}
# Identify those prefixes that designate unique values, and
# those that are the full keys
set uniquePrefixMapping {}
dict for { key valueList } $prefixMapping {
if { [llength $valueList] == 1 } {
dict set uniquePrefixMapping $key [lindex $valueList 0]
}
}
foreach { key value } $data {
dict set uniquePrefixMapping $key $value
}
# Construct the re.
return [list \
[MakeUniquePrefixRegexp $successors $uniquePrefixMapping {}] \
$uniquePrefixMapping]
}
#----------------------------------------------------------------------
#
# MakeUniquePrefixRegexp --
#
# Service procedure for 'UniquePrefixRegexp' that constructs
# a regular expresison that matches the unique prefixes.
#
# Parameters:
# successors - Dictionary whose keys are all prefixes
# of keys passed to 'UniquePrefixRegexp' and whose
# values are dictionaries whose keys are the characters
# that may follow those prefixes.
# uniquePrefixMapping - Dictionary whose keys are the unique
# prefixes and whose values are not examined.
# prefixString - Current prefix being processed.
#
# Results:
# Returns a constructed regular expression that matches the set
# of unique prefixes beginning with the 'prefixString'.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::MakeUniquePrefixRegexp { successors
uniquePrefixMapping
prefixString } {
# Get the characters that may follow the current prefix string
set schars [lsort -ascii [dict keys [dict get $successors $prefixString]]]
if { [llength $schars] == 0 } {
return {}
}
# If there is more than one successor character, or if the current
# prefix is a unique prefix, surround the generated re with non-capturing
# parentheses.
set re {}
if { [dict exists $uniquePrefixMapping $prefixString]
|| [llength $schars] > 1 } {
append re "(?:"
}
# Generate a regexp that matches the successors.
set sep ""
foreach { c } $schars {
set nextPrefix $prefixString$c
regsub -all {[^[:alnum:]]} $c \\\\& rechar
append re $sep $rechar \
[MakeUniquePrefixRegexp \
$successors $uniquePrefixMapping $nextPrefix]
set sep |
}
# If the current prefix is a unique prefix, make all following text
# optional. Otherwise, if there is more than one successor character,
# close the non-capturing parentheses.
if { [dict exists $uniquePrefixMapping $prefixString] } {
append re ")?"
} elseif { [llength $schars] > 1 } {
append re ")"
}
return $re
}
#----------------------------------------------------------------------
#
# MakeParseCodeFromFields --
#
# Composes Tcl code to extract the Julian Day Number from a
# dictionary containing date fields.
#
# Parameters:
# dateFields -- Dictionary whose keys are fields of the date,
# and whose values are the rightmost positions
# at which those fields appear.
# parseActions -- List of triples: field set, priority, and
# code to emit. Smaller priorities are better, and
# the list must be in ascending order by priority
#
# Results:
# Returns a burst of code that extracts the day number from the
# given date.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::MakeParseCodeFromFields { dateFields parseActions } {
set currPrio 999
set currFieldPos [list]
set currCodeBurst {
error "in ::tcl::clock::MakeParseCodeFromFields: can't happen"
}
foreach { fieldSet prio parseAction } $parseActions {
# If we've found an answer that's better than any that follow,
# quit now.
if { $prio > $currPrio } {
break
}
# Accumulate the field positions that are used in the current
# field grouping.
set fieldPos [list]
set ok true
foreach field $fieldSet {
if { ! [dict exists $dateFields $field] } {
set ok 0
break
}
lappend fieldPos [dict get $dateFields $field]
}
# Quit if we don't have a complete set of fields
if { !$ok } {
continue
}
# Determine whether the current answer is better than the last.
set fPos [lsort -integer -decreasing $fieldPos]
if { $prio == $currPrio } {
foreach currPos $currFieldPos newPos $fPos {
if { ![string is integer $newPos]
|| ![string is integer $currPos]
|| $newPos > $currPos } {
break
}
if { $newPos < $currPos } {
set ok 0
break
}
}
}
if { !$ok } {
continue
}
# Remember the best possibility for extracting date information
set currPrio $prio
set currFieldPos $fPos
set currCodeBurst $parseAction
}
return $currCodeBurst
}
#----------------------------------------------------------------------
#
# EnterLocale --
#
# Switch [mclocale] to a given locale if necessary
#
# Parameters:
# locale -- Desired locale
# oldLocaleVar -- Name of a variable in caller's scope that
# tracks the previous locale name.
#
# Results:
# Returns the locale that was previously current.
#
# Side effects:
# Does [mclocale]. If necessary, uses [mcload] to load the
# designated locale's files, and tracks that it has done so
# in the 'McLoaded' variable.
#
#----------------------------------------------------------------------
proc ::tcl::clock::EnterLocale { locale oldLocaleVar } {
upvar 1 $oldLocaleVar oldLocale
variable MsgDir
variable McLoaded
set oldLocale [mclocale]
if { $locale eq {system} } {
if { $::tcl_platform(platform) ne {windows} } {
# On a non-windows platform, the 'system' locale is
# the same as the 'current' locale
set locale current
} else {
# On a windows platform, the 'system' locale is
# adapted from the 'current' locale by applying the
# date and time formats from the Control Panel.
# First, load the 'current' locale if it's not yet loaded
if {![dict exists $McLoaded $oldLocale] } {
mcload $MsgDir
dict set McLoaded $oldLocale {}
}
# Make a new locale string for the system locale, and
# get the Control Panel information
set locale ${oldLocale}_windows
if { ![dict exists $McLoaded $locale] } {
LoadWindowsDateTimeFormats $locale
dict set mcloaded $locale {}
}
}
}
if { $locale eq {current}} {
set locale $oldLocale
unset oldLocale
} elseif { $locale eq $oldLocale } {
unset oldLocale
} else {
mclocale $locale
}
if { ![dict exists $McLoaded $locale] } {
mcload $MsgDir
dict set McLoaded $locale {}
}
}
#----------------------------------------------------------------------
#
# LoadWindowsDateTimeFormats --
#
# Load the date/time formats from the Control Panel in Windows
# and convert them so that they're usable by Tcl.
#
# Parameters:
# locale - Name of the locale in whose message catalog
# the converted formats are to be stored.
#
# Results:
# None.
#
# Side effects:
# Updates the given message catalog with the locale strings.
#
# Presumes that on entry, [mclocale] is set to the current locale,
# so that default strings can be obtained if the Registry query
# fails.
#
#----------------------------------------------------------------------
proc ::tcl::clock::LoadWindowsDateTimeFormats { locale } {
# Bail out if we can't find the Registry
variable NoRegistry
if { [info exists NoRegistry] } return
if { ![catch {
registry get "HKEY_CURRENT_USER\\Control Panel\\International" \
sShortDate
} string] } {
set quote {}
set datefmt {}
foreach { unquoted quoted } [split $string '] {
append datefmt $quote [string map {
dddd %A
ddd %a
dd %d
d %e
MMMM %B
MMM %b
MM %m
M %N
yyyy %Y
yy %y
y %y
gg {}
} $unquoted]
if { $quoted eq {} } {
set quote '
} else {
set quote $quoted
}
}
::msgcat::mcset $locale DATE_FORMAT $datefmt
}
if { ![catch {
registry get "HKEY_CURRENT_USER\\Control Panel\\International" \
sLongDate
} string] } {
set quote {}
set ldatefmt {}
foreach { unquoted quoted } [split $string '] {
append ldatefmt $quote [string map {
dddd %A
ddd %a
dd %d
d %e
MMMM %B
MMM %b
MM %m
M %N
yyyy %Y
yy %y
y %y
gg {}
} $unquoted]
if { $quoted eq {} } {
set quote '
} else {
set quote $quoted
}
}
::msgcat::mcset $locale LOCALE_DATE_FORMAT $ldatefmt
}
if { ![catch {
registry get "HKEY_CURRENT_USER\\Control Panel\\International" \
sTimeFormat
} string] } {
set quote {}
set timefmt {}
foreach { unquoted quoted } [split $string '] {
append timefmt $quote [string map {
HH %H
H %k
hh %I
h %l
mm %M
m %M
ss %S
s %S
tt %p
t %p
} $unquoted]
if { $quoted eq {} } {
set quote '
} else {
set quote $quoted
}
}
::msgcat::mcset $locale TIME_FORMAT $timefmt
}
catch {
::msgcat::mcset $locale DATE_TIME_FORMAT "$datefmt $timefmt"
}
catch {
::msgcat::mcset $locale LOCALE_DATE_TIME_FORMAT "$ldatefmt $timefmt"
}
return
}
#----------------------------------------------------------------------
#
# LocalizeFormat --
#
# Map away locale-dependent format groups in a clock format.
#
# Parameters:
# format -- Format supplied to [clock scan] or [clock format]
#
# Results:
# Returns the string with locale-dependent composite format
# groups substituted out.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::LocalizeFormat { format } {
# Handle locale-dependent format groups by mapping them out of
# the input string. Note that the order of the [string map]
# operations is significant because earlier formats can refer
# to later ones; for example %c can refer to %X, which in turn
# can refer to %T.
set format [string map [list %c [mc DATE_TIME_FORMAT] \
%Ec [mc LOCALE_DATE_TIME_FORMAT]] $format]
set format [string map [list %x [mc DATE_FORMAT] \
%Ex [mc LOCALE_DATE_FORMAT] \
%X [mc TIME_FORMAT] \
%EX [mc LOCALE_TIME_FORMAT]] $format]
set format [string map [list %r [mc TIME_FORMAT_12] \
%R [mc TIME_FORMAT_24] \
%T [mc TIME_FORMAT_24_SECS]] $format]
set format [string map [list %D %m/%d/%Y \
%EY [mc LOCALE_YEAR_FORMAT]\
%+ {%a %b %e %H:%M:%S %Z %Y}] $format]
return $format
}
#----------------------------------------------------------------------
#
# FormatStarDate --
#
# Formats a date as a StarDate.
#
# Parameters:
# date - Dictionary containing 'year', 'dayOfYear', and
# 'localSeconds' fields.
#
# Results:
# Returns the given date formatted as a StarDate.
#
# Side effects:
# None.
#
# Jeff Hobbs put this in to support an atrocious pun about Tcl being
# "Enterprise ready." Now we're stuck with it.
#
#----------------------------------------------------------------------
proc ::tcl::clock::FormatStarDate { date } {
variable DaysPerYear
variable SecondsPerDay
variable Roddenberry
# Get day of year, zero based
set doy [expr { [dict get $date dayOfYear] - 1 }]
# Determine whether the year is a leap year
if { [dict get $date gregorian] } {
set lp [IsGregorianLeapYear $date]
} else {
set lp [expr { [dict get $date year] % 4 == 0 }]
}
# Convert day of year to a fractional year
if { $lp } {
set fractYear [expr { 1000 * $doy / ( $DaysPerYear + 1 ) }]
} else {
set fractYear [expr { 1000 * $doy / $DaysPerYear }]
}
# Put together the StarDate
return [::format "Stardate %02d%03d.%1d" \
[expr { [dict get $date year] - $Roddenberry }] \
$fractYear \
[expr { [dict get $date localSeconds] % $SecondsPerDay
/ ( $SecondsPerDay / 10 ) }]]
}
#----------------------------------------------------------------------
#
# ParseStarDate --
#
# Parses a StarDate
#
# Parameters:
# year - Year from the Roddenberry epoch
# fractYear - Fraction of a year specifiying the day of year.
# fractDay - Fraction of a day
#
# Results:
# Returns a count of seconds from the Posix epoch.
#
# Side effects:
# None.
#
# Jeff Hobbs put this in to support an atrocious pun about Tcl being
# "Enterprise ready." Now we're stuck with it.
#
#----------------------------------------------------------------------
proc ::tcl::clock::ParseStarDate { year fractYear fractDay } {
variable Roddenberry
variable DaysPerYear
variable SecondsPerDay
variable PosixEpochAsJulianSeconds
# Build a tentative date from year and fraction.
set date [dict create \
era CE \
year [expr { $year + $Roddenberry }] \
dayOfYear [expr { $fractYear * $DaysPerYear / 1000 + 1 }]]
set date [GetJulianDayFromGregorianEraYearDay [K $date [set date {}]]]
# Determine whether the given year is a leap year
if { [dict get $date gregorian] } {
set lp [IsGregorianLeapYear $date]
} else {
set lp [expr { [dict get $date year] % 4 == 0 }]
}
# Reconvert the fractional year according to whether the given
# year is a leap year
if { $lp } {
dict set date dayOfYear \
[expr { $fractYear * ( $DaysPerYear + 1 ) / 1000 + 1 }]
} else {
dict set date dayOfYear \
[expr { $fractYear * $DaysPerYear / 1000 + 1 }]
}
dict unset date julianDay
dict unset date gregorian
set date [GetJulianDayFromGregorianEraYearDay [K $date [set date {}]]]
return [expr { $SecondsPerDay * [dict get $date julianDay]
- $PosixEpochAsJulianSeconds
+ ( $SecondsPerDay / 10 ) * $fractDay }]
}
#----------------------------------------------------------------------
#
# ScanWide --
#
# Scans a wide integer from an input
#
# Parameters:
# str - String containing a decimal wide integer
#
# Results:
# Returns the string as a pure wide integer. Throws an error if
# the string is misformatted or out of range.
#
#----------------------------------------------------------------------
proc ::tcl::clock::ScanWide { str } {
set count [::scan $str {%ld %c} result junk]
if { $count != 1 } {
return -code error -errorcode [list CLOCK notAnInteger $str] \
"\"$str\" is not an integer"
}
if { [incr result 0] != $str } {
return -code error -errorcode [list CLOCK integervalueTooLarge] \
"integer value too large to represent"
}
return $result
}
#----------------------------------------------------------------------
#
# InterpretTwoDigitYear --
#
# Given a date that contains only the year of the century,
# determines the target value of a two-digit year.
#
# Parameters:
# date - Dictionary containing fields of the date.
# baseTime - Base time relative to which the date is expressed.
# twoDigitField - Name of the field that stores the two-digit year.
# Default is 'yearOfCentury'
# fourDigitField - Name of the field that will receive the four-digit
# year. Default is 'year'
#
# Results:
# Returns the dictionary augmented with the four-digit year, stored in
# the given key.
#
# Side effects:
# None.
#
# The current rule for interpreting a two-digit year is that the year
# shall be between 1937 and 2037, thus staying within the range of a
# 32-bit signed value for time. This rule may change to a sliding
# window in future versions, so the 'baseTime' parameter (which is
# currently ignored) is provided in the procedure signature.
#
#----------------------------------------------------------------------
proc ::tcl::clock::InterpretTwoDigitYear { date baseTime
{ twoDigitField yearOfCentury }
{ fourDigitField year } } {
set yr [dict get $date $twoDigitField]
if { $yr <= 37 } {
dict set date $fourDigitField [expr { $yr + 2000 }]
} else {
dict set date $fourDigitField [expr { $yr + 1900 }]
}
return $date
}
#----------------------------------------------------------------------
#
# AssignBaseYear --
#
# Places the number of the current year into a dictionary.
#
# Parameters:
# date - Dictionary value to update
# baseTime - Base time from which to extract the year, expressed
# in seconds from the Posix epoch
#
# Results:
# Returns the dictionary with the current year assigned.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::AssignBaseYear { date baseTime timeZone } {
variable PosixEpochAsJulianSeconds
variable SecondsPerDay
# Find the Julian Day Number corresponding to the base time, and
# find the Gregorian year corresponding to that Julian Day.
set date2 [dict create seconds $baseTime]
set date2 [ConvertUTCToLocal [K $date2 [set date2 {}]] $timeZone]
set date2 [GetJulianDay [K $date2 [set date2 {}]]]
set date2 [GetGregorianEraYearDay [K $date2 [set date2 {}]]]
# Store the converted year
dict set date era [dict get $date2 era]
dict set date year [dict get $date2 year]
return $date
}
#----------------------------------------------------------------------
#
# AssignBaseIso8601Year --
#
# Determines the base year in the ISO8601 fiscal calendar.
#
# Parameters:
# date - Dictionary containing the fields of the date that
# is to be augmented with the base year.
# baseTime - Base time expressed in seconds from the Posix epoch.
#
# Results:
# Returns the given date with "iso8601Year" set to the
# base year.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::AssignBaseIso8601Year { date baseTime timeZone } {
variable PosixEpochAsJulianSeconds
variable SecondsPerDay
# Find the Julian Day Number corresponding to the base time
set date2 [dict create seconds $baseTime]
set date2 [ConvertUTCToLocal [K $date2 [set date2 {}]] $timeZone]
set date2 [GetJulianDay [K $date2 [set date2 {}]]]
# Calculate the ISO8601 date and transfer the year
set date2 [GetYearWeekDay [K $date2 [set date2 {}]]]
dict set date era CE
dict set date iso8601Year [dict get $date2 iso8601Year]
return $date
}
#----------------------------------------------------------------------
#
# AssignBaseMonth --
#
# Places the number of the current year and month into a
# dictionary.
#
# Parameters:
# date - Dictionary value to update
# baseTime - Time from which the year and month are to be
# obtained, expressed in seconds from the Posix epoch.
#
# Results:
# Returns the dictionary with the base year and month assigned.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::AssignBaseMonth { date baseTime timeZone } {
variable PosixEpochAsJulianSeconds
variable SecondsPerDay
# Find the Julian Day Number corresponding to the base time
set date2 [dict create seconds $baseTime]
set date2 [ConvertUTCToLocal [K $date2 [set date2 {}]] $timeZone]
set date2 [GetJulianDay [K $date2 [set date2 {}]]]
# Find the Gregorian year corresponding to that Julian Day
set date2 [GetGregorianEraYearDay [K $date2 [set date2 {}]]]
set date2 [GetMonthDay [K $date2 [set date2 {}]]]
dict set date era [dict get $date2 era]
dict set date year [dict get $date2 year]
dict set date month [dict get $date2 month]
return $date
}
#----------------------------------------------------------------------
#
# AssignBaseWeek --
#
# Determines the base year and week in the ISO8601 fiscal calendar.
#
# Parameters:
# date - Dictionary containing the fields of the date that
# is to be augmented with the base year and week.
# baseTime - Base time expressed in seconds from the Posix epoch.
#
# Results:
# Returns the given date with "iso8601Year" set to the
# base year and "iso8601Week" to the week number.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::AssignBaseWeek { date baseTime timeZone } {
variable PosixEpochAsJulianSeconds
variable SecondsPerDay
# Find the Julian Day Number corresponding to the base time
set date2 [dict create seconds $baseTime]
set date2 [ConvertUTCToLocal [K $date2 [set date2 {}]] $timeZone]
set date2 [GetJulianDay [K $date2 [set date2 {}]]]
# Calculate the ISO8601 date and transfer the year
set date2 [GetYearWeekDay [K $date2 [set date2 {}]]]
dict set date era CE
dict set date iso8601Year [dict get $date2 iso8601Year]
dict set date iso8601Week [dict get $date2 iso8601Week]
return $date
}
#----------------------------------------------------------------------
#
# AssignBaseJulianDay --
#
# Determines the base day for a time-of-day conversion.
#
# Parameters:
# date - Dictionary that is to get the base day
# baseTime - Base time expressed in seconds from the Posix epoch
#
# Results:
# Returns the given dictionary augmented with a 'julianDay' field
# that contains the base day.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::AssignBaseJulianDay { date baseTime timeZone } {
variable PosixEpochAsJulianSeconds
variable SecondsPerDay
# Find the Julian Day Number corresponding to the base time
set date2 [dict create seconds $baseTime]
set date2 [ConvertUTCToLocal [K $date2 [set date2 {}]] $timeZone]
set date2 [GetJulianDay [K $date2 [set date2 {}]]]
dict set date julianDay [dict get $date2 julianDay]
return $date
}
#----------------------------------------------------------------------
#
# InterpretHMSP --
#
# Interprets a time in the form "hh:mm:ss am".
#
# Parameters:
# date -- Dictionary containing "hourAMPM", "minute", "second"
# and "amPmIndicator" fields.
#
# Results:
# Returns the number of seconds from local midnight.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::InterpretHMSP { date } {
set hr [dict get $date hourAMPM]
if { $hr == 12 } {
set hr 0
}
if { [dict get $date amPmIndicator] } {
incr hr 12
}
dict set date hour $hr
return [InterpretHMS [K $date [set date {}]]]
}
#----------------------------------------------------------------------
#
# InterpretHMS --
#
# Interprets a 24-hour time "hh:mm:ss"
#
# Parameters:
# date -- Dictionary containing the "hour", "minute" and "second"
# fields.
#
# Results:
# Returns the given dictionary augmented with a "secondOfDay"
# field containing the number of seconds from local midnight.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::InterpretHMS { date } {
variable SecondsPerMinute
variable MinutesPerHour
return [expr { ( [dict get $date hour] * $MinutesPerHour
+ [dict get $date minute] ) * $SecondsPerMinute
+ [dict get $date second] }]
}
#----------------------------------------------------------------------
#
# GetSystemTimeZone --
#
# Determines the system time zone, which is the default for the
# 'clock' command if no other zone is supplied.
#
# Parameters:
# None.
#
# Results:
# Returns the system time zone.
#
# Side effects:
# Stores the sustem time zone in the 'CachedSystemTimeZone'
# variable, since determining it may be an expensive process.
#
#----------------------------------------------------------------------
proc ::tcl::clock::GetSystemTimeZone {} {
variable CachedSystemTimeZone
if { [info exists ::env(TCL_TZ)] } {
set timezone $::env(TCL_TZ)
} elseif { [info exists ::env(TZ)] } {
set timezone $::env(TZ)
} elseif { $::tcl_platform(platform) eq {windows} } {
if { [info exists CachedSystemTimeZone] } {
set timezone $CachedSystemTimeZone
} else {
set timezone [GuessWindowsTimeZone]
set CachedSystemTimeZone $timezone
}
} else {
set timezone :localtime
}
if { [catch {SetupTimeZone $timezone}] } {
set timezone :localtime
}
return $timezone
}
#----------------------------------------------------------------------
#
# ConvertLegacyTimeZone --
#
# Given an alphanumeric time zone identifier and the system
# time zone, convert the alphanumeric identifier to an
# unambiguous time zone.
#
# Parameters:
# tzname - Name of the time zone to convert
#
# Results:
# Returns a time zone name corresponding to tzname, but
# in an unambiguous form, generally +hhmm.
#
# This procedure is implemented primarily to allow the parsing of
# RFC822 date/time strings. Processing a time zone name on input
# is not recommended practice, because there is considerable room
# for ambiguity; for instance, is BST Brazilian Standard Time, or
# British Summer Time?
#
#----------------------------------------------------------------------
proc ::tcl::clock::ConvertLegacyTimeZone { tzname } {
variable LegacyTimeZone
set tzname [string tolower $tzname]
if { ![dict exists $LegacyTimeZone $tzname] } {
return -code error -errorcode [list CLOCK badTZName $tzname] \
"time zone \"$tzname\" not found"
} else {
return [dict get $LegacyTimeZone $tzname]
}
}
#----------------------------------------------------------------------
#
# ConvertLocalToUTC --
#
# Given a time zone and nominal local seconds, compute seconds
# of UTC time from the Posix epoch.
#
# Parameters:
# date - Dictionary populated with the 'localSeconds' and
# 'tzName' fields
#
# Results:
# Returns the given dictionary augmented with a 'seconds' field.
#
#----------------------------------------------------------------------
proc ::tcl::clock::ConvertLocalToUTC { date } {
variable TZData
set timezone [dict get $date tzName]
if { $timezone eq ":localtime" } {
# Convert using the mktime function if possible
if { [catch {
ConvertLocalToUTCViaC [dict get $date localSeconds]
} result] } {
return -code error -errorcode $::errorCode $result
}
dict set date seconds $result
return $date
} else {
# Get the time zone data
if { [catch { SetupTimeZone $timezone } retval] } {
return -code error -errorcode $::errorCode $retval
}
# Initially assume that local == UTC, and locate the last time
# conversion prior to that time. Get the offset from that,
# and look up again. If that lookup finds a different offset,
# continue looking until we find an offset that we found
# before. The check for "any offset previously found" rather
# than "the same offset" avoids an endless loop if we try to
# convert a non-existent time, for example 2:30am during the
# US spring DST change.
set localseconds [dict get $date localSeconds]
set utcseconds(0) $localseconds
set seconds $localseconds
while { 1 } {
set i [BSearch $TZData($timezone) $seconds]
set offset [lindex $TZData($timezone) $i 1]
if { [info exists utcseconds($offset)] } {
dict set date seconds $utcseconds($offset)
return $date
} else {
set seconds [expr { $localseconds - $offset }]
set utcseconds($offset) $seconds
}
}
# In the absolute worst case, the loop above can visit each tzdata
# row only once, so it's guaranteed to terminate.
error "in ConvertLocalToUTC, can't happen"
}
}
#----------------------------------------------------------------------
#
# ConvertLocalToUTCViaC --
#
# Given seconds of nominal local time, compute seconds from the
# Posix epoch.
#
# Parameters:
# localSeconds - Seconds of nominal local time
#
# Results:
# Returns the seconds from the epoch. May throw an error if
# the time is to large/small to represent, or if 'mktime' is
# not present in the C library.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::ConvertLocalToUTCViaC { localSeconds } {
variable SecondsPerHour
variable SecondsPerMinute
variable MinutesPerHour
variable HoursPerDay
set date [dict create localSeconds $localSeconds]
set date [GetJulianDay [K $date [set date {}]]]
set date [GetGregorianEraYearDay [K $date [set date {}]]]
set date [GetMonthDay [K $date [set date {}]]]
set retval \
[Mktime \
[dict get $date year] \
[dict get $date month] \
[dict get $date dayOfMonth] \
[expr { $localSeconds / $SecondsPerHour % $HoursPerDay }] \
[expr { $localSeconds / $SecondsPerMinute % $MinutesPerHour }] \
[expr { $localSeconds % $SecondsPerMinute }]]
return $retval
}
#----------------------------------------------------------------------
#
# ConvertUTCToLocal --
#
# Given the seconds from the Posix epoch, compute seconds of
# nominal local time.
#
# Parameters:
# date - Dictionary populated on entry with the 'seconds' field
#
# Results:
# The given dictionary is returned, augmented with 'localSeconds',
# 'tzOffset', and 'tzName' fields.
#
#----------------------------------------------------------------------
proc ::tcl::clock::ConvertUTCToLocal { date timezone } {
variable TZData
# Get the data for time changes in the given zone
if { [catch { SetupTimeZone $timezone } retval] } {
return -code error -errorcode $::errorCode $retval
}
if { $timezone eq {:localtime} } {
# Convert using the localtime function
if { [catch {
ConvertUTCToLocalViaC $date
} retval] } {
return -code error -errorcode $::errorCode $retval
}
return $retval
}
# Find the most recent transition in the time zone data
set i [BSearch $TZData($timezone) [dict get $date seconds]]
set row [lindex $TZData($timezone) $i]
foreach { junk1 offset junk2 name } $row break
# Add appropriate offset to convert Greenwich to local, and return
# the local time
dict set date localSeconds [expr { [dict get $date seconds] + $offset }]
dict set date tzOffset $offset
dict set date tzName $name
return $date
}
#----------------------------------------------------------------------
#
# ConvertUTCToLocalViaC --
#
# Convert local time using the C localtime function
#
# Parameters:
# date - Dictionary populated on entry with the 'seconds'
# and 'timeZone' fields.
#
# Results:
# The given dictionary is returned, augmented with 'localSeconds',
# 'tzOffset', and 'tzName' fields.
#
#----------------------------------------------------------------------
proc ::tcl::clock::ConvertUTCToLocalViaC { date } {
variable PosixEpochAsJulianSeconds
variable SecondsPerMinute
variable SecondsPerHour
variable MinutesPerHour
variable HoursPerDay
# Get y-m-d-h-m-s from the C library
set gmtSeconds [dict get $date seconds]
set localFields [Localtime $gmtSeconds]
set date2 [dict create]
foreach key {
year month dayOfMonth hour minute second
} value $localFields {
dict set date2 $key $value
}
dict set date2 era CE
# Convert to Julian Day
set date2 [GetJulianDayFromEraYearMonthDay [K $date2 [set date2 {}]]]
# Reconvert to seconds from the epoch in local time.
set localSeconds [expr { ( ( ( wide([dict get $date2 julianDay])
* $HoursPerDay
+ wide([dict get $date2 hour]) )
* $MinutesPerHour
+ wide([dict get $date2 minute]) )
* $SecondsPerMinute
+ wide([dict get $date2 second]) )
- $PosixEpochAsJulianSeconds }]
# Determine the name and offset of the timezone
set delta [expr { $localSeconds - $gmtSeconds }]
if { $delta <= 0 } {
set signum -
set delta [expr { - $delta }]
} else {
set signum +
}
set hh [::format %02d [expr { $delta / $SecondsPerHour }]]
set mm [::format %02d [expr { ($delta / $SecondsPerMinute )
% $MinutesPerHour }]]
set ss [::format %02d [expr { $delta % $SecondsPerMinute }]]
set zoneName $signum$hh$mm
if { $ss ne {00} } {
append zoneName $ss
}
# Fix the dictionary
dict set date localSeconds $localSeconds
dict set date tzOffset $delta
dict set date tzName $zoneName
return $date
}
#----------------------------------------------------------------------
#
# SetupTimeZone --
#
# Given the name or specification of a time zone, sets up
# its in-memory data.
#
# Parameters:
# tzname - Name of a time zone
#
# Results:
# Unless the time zone is ':localtime', sets the TZData array
# to contain the lookup table for local<->UTC conversion.
# Returns an error if the time zone cannot be parsed.
#
#----------------------------------------------------------------------
proc ::tcl::clock::SetupTimeZone { timezone } {
variable TZData
variable MinutesPerHour
variable SecondsPerMinute
variable MINWIDE
if {! [info exists TZData($timezone)] } {
if { $timezone eq {:localtime} } {
# Nothing to do, we'll convert using the localtime function
} elseif { [regexp {^([-+])(\d\d):?(\d\d)(?::?(\d\d))?} $timezone \
-> s hh mm ss] } {
# Make a fixed offset
::scan $hh %d hh
::scan $mm %d mm
if { $ss eq {} } {
set ss 0
} else {
::scan $ss %d ss
}
set offset [expr { ( $hh * $MinutesPerHour
+ $mm ) * $SecondsPerMinute
+ $ss }]
if { $s eq {-} } {
set offset [expr { - $offset }]
}
set TZData($timezone) [list [list $MINWIDE $offset -1 $timezone]]
} elseif { [string index $timezone 0] eq {:} } {
# Convert using a time zone file
if {
[catch {
LoadTimeZoneFile [string range $timezone 1 end]
}]
&& [catch {
LoadZoneinfoFile [string range $timezone 1 end]
}]
} {
return -code error \
-errorcode [list CLOCK badTimeZone $timezone] \
"time zone \"$timezone\" not found"
}
} elseif { ![catch {ParsePosixTimeZone $timezone} tzfields] } {
# This looks like a POSIX time zone - try to process it
if { [catch {ProcessPosixTimeZone $tzfields} data] } {
if { [lindex $::errorCode 0] eq {CLOCK} } {
return -code error -errorcode $::errorCode $data
} else {
error $tzfields $::errorInfo $::errorCode
}
} else {
set TZData($timezone) $data
}
} else {
# We couldn't parse this as a POSIX time zone. Try
# again with a time zone file - this time without a colon
if { [catch { LoadTimeZoneFile $timezone }]
&& [catch { LoadZoneinfoFile $timezone }] } {
return -code error -errorcode $::errorCode \
"time zone $timezone not found"
}
set TZData($timezone) $TZData(:$timezone)
}
}
return
}
#----------------------------------------------------------------------
#
# GuessWindowsTimeZone --
#
# Determines the system time zone on windows.
#
# Parameters:
# None.
#
# Results:
# Returns a time zone specifier that corresponds to the system
# time zone information found in the Registry.
#
# Bugs:
# Fixed dates for DST change are unimplemented at present, because
# no time zone information supplied with Windows actually uses
# them!
#
# On a Windows system where neither $env(TCL_TZ) nor $env(TZ) is
# specified, GuessWindowsTimeZone looks in the Registry for the
# system time zone information. It then attempts to find an entry
# in WinZoneInfo for a time zone that uses the same rules. If
# it finds one, it returns it; otherwise, it constructs a Posix-style
# time zone string and returns that.
#
#----------------------------------------------------------------------
proc ::tcl::clock::GuessWindowsTimeZone {} {
variable WinZoneInfo
variable SecondsPerHour
variable SecondsPerMinute
variable MinutesPerHour
variable NoRegistry
if { [info exists NoRegistry] } {
return :localtime
}
# Dredge time zone information out of the registry
if { [catch {
set rpath HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\TimeZoneInformation
set data [list \
[expr { -$SecondsPerMinute
* [registry get $rpath Bias] }] \
[expr { -$SecondsPerMinute \
* [registry get $rpath StandardBias] }] \
[expr { -$SecondsPerMinute \
* [registry get $rpath DaylightBias] }]]
set stdtzi [registry get $rpath StandardStart]
foreach ind {0 2 14 4 6 8 10 12} {
binary scan $stdtzi @${ind}s val
lappend data $val
}
set daytzi [registry get $rpath DaylightStart]
foreach ind {0 2 14 4 6 8 10 12} {
binary scan $daytzi @${ind}s val
lappend data $val
}
}] } {
# Missing values in the Registry - bail out
return :localtime
}
# Make up a Posix time zone specifier if we can't find one
if { ! [dict exists $WinZoneInfo $data] } {
foreach {
bias stdBias dstBias
stdYear stdMonth stdDayOfWeek stdDayOfMonth
stdHour stdMinute stdSecond stdMillisec
dstYear dstMonth dstDayOfWeek dstDayOfMonth
dstHour dstMinute dstSecond dstMillisec
} $data break
set stdDelta [expr { $bias + $stdBias }]
set dstDelta [expr { $bias + $dstBias }]
if { $stdDelta <= 0 } {
set stdSignum +
set stdDelta [expr { - $stdDelta }]
} else {
set stdSignum -
}
set hh [::format %02d [expr { $stdDelta / $SecondsPerHour }]]
set mm [::format %02d [expr { ($stdDelta / $SecondsPerMinute )
% $MinutesPerHour }]]
set ss [::format %02d [expr { $stdDelta % $SecondsPerMinute }]]
append tzname < $stdSignum $hh $mm > $stdSignum $hh : $mm : $ss
if { $stdMonth >= 0 } {
if { $dstDelta <= 0 } {
set dstSignum +
set dstDelta [expr { - $dstDelta }]
} else {
set dstSignum -
}
set hh [::format %02d [expr { $dstDelta / $SecondsPerHour }]]
set mm [::format %02d [expr { ($dstDelta / $SecondsPerMinute )
% $MinutesPerHour }]]
set ss [::format %02d [expr { $dstDelta % $SecondsPerMinute }]]
append tzname < $dstSignum $hh $mm > $dstSignum $hh : $mm : $ss
if { $dstYear == 0 } {
append tzname ,M $dstMonth . $dstDayOfMonth . $dstDayOfWeek
} else {
# I have not been able to find any locale on which
# Windows converts time zone on a fixed day of the year,
# hence don't know how to interpret the fields.
# If someone can inform me, I'd be glad to code it up.
# For right now, we bail out in such a case.
return :localtime
}
append tzname / [::format %02d $dstHour] \
: [::format %02d $dstMinute] \
: [::format %02d $dstSecond]
if { $stdYear == 0 } {
append tzname ,M $stdMonth . $stdDayOfMonth . $stdDayOfWeek
} else {
# I have not been able to find any locale on which
# Windows converts time zone on a fixed day of the year,
# hence don't know how to interpret the fields.
# If someone can inform me, I'd be glad to code it up.
# For right now, we bail out in such a case.
return :localtime
}
append tzname / [::format %02d $stdHour] \
: [::format %02d $stdMinute] \
: [::format %02d $stdSecond]
}
dict set WinZoneInfo $data $tzname
}
return [dict get $WinZoneInfo $data]
}
#----------------------------------------------------------------------
#
# LoadTimeZoneFile --
#
# Load the data file that specifies the conversion between a
# given time zone and Greenwich.
#
# Parameters:
# fileName -- Name of the file to load
#
# Results:
# None.
#
# Side effects:
# TZData(:fileName) contains the time zone data
#
#----------------------------------------------------------------------
proc ::tcl::clock::LoadTimeZoneFile { fileName } {
variable DataDir
variable TZData
if { [info exists TZData($fileName)] } {
return
}
# Since an unsafe interp uses the [clock] command in the master,
# this code is security sensitive. Make sure that the path name
# cannot escape the given directory.
if { ![regexp {^[[:alpha:]_]+(?:/[[:alpha:]_]+)*$} $fileName] } {
return -code error \
-errorcode [list CLOCK badTimeZone $:fileName] \
"time zone \":$fileName\" not valid"
}
if { [catch {
source -encoding utf-8 [file join $DataDir $fileName]
}] } {
return -code error \
-errorcode [list CLOCK badTimeZone :$fileName] \
"time zone \":$fileName\" not found"
}
return
}
#----------------------------------------------------------------------
#
# LoadZoneinfoFile --
#
# Loads a binary time zone information file in Olson format.
#
# Parameters:
# fileName - Path name of the file to load.
#
# Results:
# Returns an empty result normally; returns an error if no
# Olson file was found or the file was malformed in some way.
#
# Side effects:
# TZData(:fileName) contains the time zone data
#
#----------------------------------------------------------------------
proc ::tcl::clock::LoadZoneinfoFile { fileName } {
variable MINWIDE
variable TZData
variable ZoneinfoPaths
# Since an unsafe interp uses the [clock] command in the master,
# this code is security sensitive. Make sure that the path name
# cannot escape the given directory.
if { ![regexp {^[[:alpha:]_]+(?:/[[:alpha:]_]+)*$} $fileName] } {
return -code error \
-errorcode [list CLOCK badTimeZone $:fileName] \
"time zone \":$fileName\" not valid"
}
foreach d $ZoneinfoPaths {
set fname [file join $d $fileName]
if { [file readable $fname] && [file isfile $fname] } {
break
}
unset fname
}
if { ![info exists fname] } {
return -code error "$fileName not found"
}
if { [file size $fname] > 262144 } {
return -code error "$fileName too big"
}
# Suck in all the data from the file
set f [open $fname r]
fconfigure $f -translation binary
set d [read $f]
close $f
# The file begins with a magic number, sixteen reserved bytes,
# and then six 4-byte integers giving counts of fileds in the file.
binary scan $d a4x16IIIIII magic nIsGMT mIsStd nLeap nTime nType nChar
set seek 44
if { $magic != {TZif} } {
return -code error "$fileName not a time zone information file"
}
if { $nType > 255 } {
return -code error "$fileName contains too many time types"
}
if { $nLeap != 0 } {
return -code error "$fileName contains leap seconds"
}
# Next come ${nTime} transition times, followed by ${nTime} time type
# codes. The type codes are unsigned 1-byte quantities. We insert an
# arbitrary start time in front of the transitions.
binary scan $d @${seek}I${nTime}c${nTime} times tempCodes
incr seek [expr { 5 * $nTime }]
set times [linsert $times 0 $MINWIDE]
set codes {}
foreach c $tempCodes {
lappend codes [expr { $c & 0xff }]
}
set codes [linsert $codes 0 0]
# Next come ${nType} time type descriptions, each of which has an
# offset (seconds east of GMT), a DST indicator, and an index into
# the abbreviation text.
for { set i 0 } { $i < $nType } { incr i } {
binary scan $d @${seek}Icc gmtOff isDst abbrInd
lappend types [list $gmtOff $isDst $abbrInd]
incr seek 6
}
# Next come $nChar characters of time zone name abbreviations,
# which are null-terminated.
# We build them up into a dictionary indexed by character index,
# because that's what's in the indices above.
binary scan $d @${seek}a${nChar} abbrs
incr seek ${nChar}
set abbrList [split $abbrs \0]
set i 0
set abbrevs {}
foreach a $abbrList {
dict set abbrevs $i $a
incr i [expr { [string length $a] + 1 }]
}
# The rest of the data in the file are not used at present.
# Package up a list of tuples, each of which contains transition time,
# seconds east of Greenwich, DST flag and time zone abbreviation.
set r {}
set lastTime $MINWIDE
foreach t $times c $codes {
if { $t < $lastTime } {
return -code error "$fileName has times out of order"
}
set lastTime $t
foreach { gmtoff isDst abbrInd } [lindex $types $c] break
set abbrev [dict get $abbrevs $abbrInd]
lappend r [list $t $gmtoff $isDst $abbrev]
}
set TZData(:$fileName) $r
}
#----------------------------------------------------------------------
#
# ParsePosixTimeZone --
#
# Parses the TZ environment variable in Posix form
#
# Parameters:
# tz Time zone specifier to be interpreted
#
# Results:
# Returns a dictionary whose values contain the various pieces of
# the time zone specification.
#
# Side effects:
# None.
#
# Errors:
# Throws an error if the syntax of the time zone is incorrect.
#
# The following keys are present in the dictionary:
# stdName - Name of the time zone when Daylight Saving Time
# is not in effect.
# stdSignum - Sign (+, -, or empty) of the offset from Greenwich
# to the given (non-DST) time zone. + and the empty
# string denote zones west of Greenwich, - denotes east
# of Greenwich; this is contrary to the ISO convention
# but follows Posix.
# stdHours - Hours part of the offset from Greenwich to the given
# (non-DST) time zone.
# stdMinutes - Minutes part of the offset from Greenwich to the
# given (non-DST) time zone. Empty denotes zero.
# stdSeconds - Seconds part of the offset from Greenwich to the
# given (non-DST) time zone. Empty denotes zero.
# dstName - Name of the time zone when DST is in effect, or the
# empty string if the time zone does not observe Daylight
# Saving Time.
# dstSignum, dstHours, dstMinutes, dstSeconds -
# Fields corresponding to stdSignum, stdHours, stdMinutes,
# stdSeconds for the Daylight Saving Time version of the
# time zone. If dstHours is empty, it is presumed to be 1.
# startDayOfYear - The ordinal number of the day of the year on which
# Daylight Saving Time begins. If this field is
# empty, then DST begins on a given month-week-day,
# as below.
# startJ - The letter J, or an empty string. If a J is present in
# this field, then startDayOfYear does not count February 29
# even in leap years.
# startMonth - The number of the month in which Daylight Saving Time
# begins, supplied if startDayOfYear is empty. If both
# startDayOfYear and startMonth are empty, then US rules
# are presumed.
# startWeekOfMonth - The number of the week in the month in which
# Daylight Saving Time begins, in the range 1-5.
# 5 denotes the last week of the month even in a
# 4-week month.
# startDayOfWeek - The number of the day of the week (Sunday=0,
# Saturday=6) on which Daylight Saving Time begins.
# startHours - The hours part of the time of day at which Daylight
# Saving Time begins. An empty string is presumed to be 2.
# startMinutes - The minutes part of the time of day at which DST begins.
# An empty string is presumed zero.
# startSeconds - The seconds part of the time of day at which DST begins.
# An empty string is presumed zero.
# endDayOfYear, endJ, endMonth, endWeekOfMonth, endDayOfWeek,
# endHours, endMinutes, endSeconds -
# Specify the end of DST in the same way that the start* fields
# specify the beginning of DST.
#
# This procedure serves only to break the time specifier into fields.
# No attempt is made to canonicalize the fields or supply default values.
#
#----------------------------------------------------------------------
proc ::tcl::clock::ParsePosixTimeZone { tz } {
if {[regexp -expanded -nocase -- {
^
# 1 - Standard time zone name
([[:alpha:]]+ | <[-+[:alnum:]]+>)
# 2 - Standard time zone offset, signum
([-+]?)
# 3 - Standard time zone offset, hours
([[:digit:]]{1,2})
(?:
# 4 - Standard time zone offset, minutes
: ([[:digit:]]{1,2})
(?:
# 5 - Standard time zone offset, seconds
: ([[:digit:]]{1,2} )
)?
)?
(?:
# 6 - DST time zone name
([[:alpha:]]+ | <[-+[:alnum:]]+>)
(?:
(?:
# 7 - DST time zone offset, signum
([-+]?)
# 8 - DST time zone offset, hours
([[:digit:]]{1,2})
(?:
# 9 - DST time zone offset, minutes
: ([[:digit:]]{1,2})
(?:
# 10 - DST time zone offset, seconds
: ([[:digit:]]{1,2})
)?
)?
)?
(?:
,
(?:
# 11 - Optional J in n and Jn form 12 - Day of year
( J ? ) ( [[:digit:]]+ )
| M
# 13 - Month number 14 - Week of month 15 - Day of week
( [[:digit:]] + )
[.] ( [[:digit:]] + )
[.] ( [[:digit:]] + )
)
(?:
# 16 - Start time of DST - hours
/ ( [[:digit:]]{1,2} )
(?:
# 17 - Start time of DST - minutes
: ( [[:digit:]]{1,2} )
(?:
# 18 - Start time of DST - seconds
: ( [[:digit:]]{1,2} )
)?
)?
)?
,
(?:
# 19 - Optional J in n and Jn form 20 - Day of year
( J ? ) ( [[:digit:]]+ )
| M
# 21 - Month number 22 - Week of month 23 - Day of week
( [[:digit:]] + )
[.] ( [[:digit:]] + )
[.] ( [[:digit:]] + )
)
(?:
# 24 - End time of DST - hours
/ ( [[:digit:]]{1,2} )
(?:
# 25 - End time of DST - minutes
: ( [[:digit:]]{1,2} )
(?:
# 26 - End time of DST - seconds
: ( [[:digit:]]{1,2} )
)?
)?
)?
)?
)?
)?
$
} $tz -> x(stdName) x(stdSignum) x(stdHours) x(stdMinutes) x(stdSeconds) \
x(dstName) x(dstSignum) x(dstHours) x(dstMinutes) x(dstSeconds) \
x(startJ) x(startDayOfYear) \
x(startMonth) x(startWeekOfMonth) x(startDayOfWeek) \
x(startHours) x(startMinutes) x(startSeconds) \
x(endJ) x(endDayOfYear) \
x(endMonth) x(endWeekOfMonth) x(endDayOfWeek) \
x(endHours) x(endMinutes) x(endSeconds)] } {
# it's a good timezone
return [array get x]
} else {
return -code error\
-errorcode [list CLOCK badTimeZone $tz] \
"unable to parse time zone specification \"$tz\""
}
}
#----------------------------------------------------------------------
#
# ProcessPosixTimeZone --
#
# Handle a Posix time zone after it's been broken out into
# fields.
#
# Parameters:
# z - Dictionary returned from 'ParsePosixTimeZone'
#
# Results:
# Returns time zone information for the 'TZData' array.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::ProcessPosixTimeZone { z } {
variable MINWIDE
variable SecondsPerMinute
variable MinutesPerHour
variable TZData
# Determine the standard time zone name and seconds east of Greenwich
set stdName [dict get $z stdName]
if { [string index $stdName 0] eq {<} } {
set stdName [string range $stdName 1 end-1]
}
if { [dict get $z stdSignum] eq {-} } {
set stdSignum +1
} else {
set stdSignum -1
}
set stdHours [lindex [::scan [dict get $z stdHours] %d] 0]
if { [dict get $z stdMinutes] ne {} } {
set stdMinutes [lindex [::scan [dict get $z stdMinutes] %d] 0]
} else {
set stdMinutes 0
}
if { [dict get $z stdSeconds] ne {} } {
set stdSeconds [lindex [::scan [dict get $z stdSeconds] %d] 0]
} else {
set stdSeconds 0
}
set stdOffset [expr { ( ( $stdHours * $MinutesPerHour + $stdMinutes )
* $SecondsPerMinute + $stdSeconds )
* $stdSignum }]
set data [list [list $MINWIDE $stdOffset 0 $stdName]]
# If there's no daylight zone, we're done
set dstName [dict get $z dstName]
if { $dstName eq {} } {
return $data
}
if { [string index $dstName 0] eq {<} } {
set dstName [string range $dstName 1 end-1]
}
# Determine the daylight name
if { [dict get $z dstSignum] eq {-} } {
set dstSignum +1
} else {
set dstSignum -1
}
if { [dict get $z dstHours] eq {} } {
set dstOffset [expr { 3600 + $stdOffset }]
} else {
set dstHours [lindex [::scan [dict get $z dstHours] %d] 0]
if { [dict get $z dstMinutes] ne {} } {
set dstMinutes [lindex [::scan [dict get $z dstMinutes] %d] 0]
} else {
set dstMinutes 0
}
if { [dict get $z dstSeconds] ne {} } {
set dstSeconds [lindex [::scan [dict get $z dstSeconds] %d] 0]
} else {
set dstSeconds 0
}
set dstOffset [expr { ( ( $dstHours * $MinutesPerHour + $dstMinutes )
* $SecondsPerMinute + $dstSeconds )
* $dstSignum }]
}
# Fill in defaults for US DST rules
if { [dict get $z startDayOfYear] eq {}
&& [dict get $z startMonth] eq {} } {
dict set z startMonth 4
dict set z startWeekOfMonth 1
dict set z startDayOfWeek 0
dict set z startHours 2
dict set z startMinutes 0
dict set z startSeconds 0
}
if { [dict get $z endDayOfYear] eq {}
&& [dict get $z endMonth] eq {} } {
dict set z endMonth 10
dict set z endWeekOfMonth 5
dict set z endDayOfWeek 0
dict set z endHours 2
dict set z endMinutes 0
dict set z endSeconds 0
}
# Put DST in effect in all years from 1916 to 2099.
for { set y 1916 } { $y < 2099 } { incr y } {
set startTime [DeterminePosixDSTTime $z start $y]
incr startTime [expr { - wide($stdOffset) }]
set endTime [DeterminePosixDSTTime $z end $y]
incr endTime [expr { - wide($dstOffset) }]
if { $startTime < $endTime } {
lappend data \
[list $startTime $dstOffset 1 $dstName] \
[list $endTime $stdOffset 0 $stdName]
} else {
lappend data \
[list $endTime $stdOffset 0 $stdName] \
[list $startTime $dstOffset 1 $dstName]
}
}
return $data
}
#----------------------------------------------------------------------
#
# DeterminePosixDSTTime --
#
# Determines the time that Daylight Saving Time starts or ends
# from a Posix time zone specification.
#
# Parameters:
# z - Time zone data returned from ParsePosixTimeZone.
# Missing fields are expected to be filled in with
# default values.
# bound - The word 'start' or 'end'
# y - The year for which the transition time is to be determined.
#
# Results:
# Returns the transition time as a count of seconds from
# the epoch. The time is relative to the wall clock, not UTC.
#
#----------------------------------------------------------------------
proc ::tcl::clock::DeterminePosixDSTTime { z bound y } {
variable FEB_28
variable PosixEpochAsJulianSeconds
variable SecondsPerDay
variable SecondsPerMinute
variable MinutesPerHour
# Determine the start or end day of DST
set date [dict create era CE year $y]
set doy [dict get $z ${bound}DayOfYear]
if { $doy ne {} } {
# Time was specified as a day of the year
if { [dict get $z ${bound}J] ne {}
&& [IsGregorianLeapYear $y]
&& ( $doy > $FEB_28 ) } {
incr doy
}
dict set date dayOfYear $doy
set date [GetJulianDayFromEraYearDay [K $date [set date {}]]]
} else {
# Time was specified as a day of the week within a month
dict set date month [dict get $z ${bound}Month]
dict set date dayOfWeekInMonth [dict get $z ${bound}WeekOfMonth]
set dow [dict get $z ${bound}DayOfWeek]
if { $dow >= 5 } {
set dow -1
}
dict set date dayOfWeek $dow
set date [GetJulianDayFromEraYearMonthWeekDay [K $date [set date {}]]]
}
set jd [dict get $date julianDay]
set seconds [expr { wide($jd) * wide($SecondsPerDay)
- wide($PosixEpochAsJulianSeconds) }]
set h [dict get $z ${bound}Hours]
if { $h eq {} } {
set h 2
} else {
set h [lindex [::scan $h %d] 0]
}
set m [dict get $z ${bound}Minutes]
if { $m eq {} } {
set m 0
} else {
set m [lindex [::scan $m %d] 0]
}
set s [dict get $z ${bound}Seconds]
if { $s eq {} } {
set s 0
} else {
set s [lindex [::scan $s %d] 0]
}
set tod [expr { ( $h * $MinutesPerHour + $m ) * $SecondsPerMinute + $s }]
return [expr { $seconds + $tod }]
}
#----------------------------------------------------------------------
#
# GetLocaleEra --
#
# Given local time expressed in seconds from the Posix epoch,
# determine localized era and year within the era.
#
# Parameters:
# date - Dictionary that must contain the keys, 'localSeconds',
# whose value is expressed as the appropriate local time;
# and 'year', whose value is the Gregorian year.
#
# Results:
# Returns the dictionary, augmented with the keys, 'localeEra'
# and 'localeYear'.
#
#----------------------------------------------------------------------
proc ::tcl::clock::GetLocaleEra { date } {
set etable [mc LOCALE_ERAS]
set index [BSearch $etable [dict get $date localSeconds]]
if { $index < 0 } {
dict set date localeEra \
[::format %02d [expr { [dict get $date year] / 100 }]]
dict set date localeYear \
[expr { [dict get $date year] % 100 }]
} else {
dict set date localeEra [lindex $etable $index 1]
dict set date localeYear [expr { [dict get $date year]
- [lindex $etable $index 2] }]
}
return $date
}
#----------------------------------------------------------------------
#
# GetJulianDay --
#
# Given the seconds from the Posix epoch, derives the Julian
# day number.
#
# Parameters:
# date - Dictionary containing the date fields. On input,
# populated with a 'localSeconds' field that gives the
# nominal seconds from the epoch (in the local time zone,
# rather than UTC).
#
# Results:
# Returns the given dictionary, augmented by a 'julianDay'
# field that gives the Julian Day Number at noon of the current
# date.
#
#----------------------------------------------------------------------
proc ::tcl::clock::GetJulianDay { date } {
variable PosixEpochAsJulianSeconds
variable SecondsPerDay
set secs [dict get $date localSeconds]
return [dict set date julianDay \
[expr { ( $secs + $PosixEpochAsJulianSeconds )
/ $SecondsPerDay }]]
}
#----------------------------------------------------------------------
#
# GetGregorianEraYearDay --
#
# Given the time from the Posix epoch and the current time zone,
# develops the era, year, and day of year in the Gregorian calendar.
#
# Parameters:
# date - Dictionary containing the date fields. On input, populated
# with the 'julianDay' key whose value is the Julian Day Number.
#
# Results:
# Returns the given dictionary with the 'gregorian', 'era',
# 'year', and 'dayOfYear' populated.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::GetGregorianEraYearDay { date } {
variable JD0Jan1CEGreg
variable JD0Jan1CEJul
variable DaysPer400Yr
variable DaysPerCentury
variable DaysPer4Yr
variable DaysPerYear
set jday [dict get $date julianDay]
set changeover [mc GREGORIAN_CHANGE_DATE]
if { $jday >= $changeover } {
# Gregorian date
dict set date gregorian 1
# Calculate number of days since 1 January, 1 CE
set day [expr { $jday - $JD0Jan1CEGreg - 1 }]
# Calculate number of 400 year cycles
set year 1
set n [expr { $day / $DaysPer400Yr }]
incr year [expr { 400 * $n }]
set day [expr { $day % $DaysPer400Yr }]
# Calculate number of centuries in the current cycle
set n [expr { $day / $DaysPerCentury }]
set day [expr { $day % $DaysPerCentury }]
if { $n > 3 } {
set n 3 ;# 31 December 2000, for instance
incr day $DaysPerCentury ;# is last day of 400 year cycle
}
incr year [expr { 100 * $n }]
} else {
# Julian date
dict set date gregorian 0
# Calculate days since 0 January, 1 CE Julian
set day [expr { $jday - $JD0Jan1CEJul - 1 }]
set year 1
}
# Calculate number of 4-year cycles in current century (or in
# the Common Era, if the calendar is Julian)
set n [expr { $day / $DaysPer4Yr }]
set day [expr { $day % $DaysPer4Yr }]
incr year [expr { 4 * $n }]
# Calculate number of years in current 4-year cycle
set n [expr { $day / $DaysPerYear }]
set day [expr { $day % $DaysPerYear }]
if { $n > 3 } {
set n 3 ;# 31 December in a leap year
incr day $DaysPerYear
}
incr year $n
# Calculate the era
if { $year <= 0 } {
dict set date year [expr { 1 - $year }]
dict set date era BCE
} else {
dict set date year $year
dict set date era CE
}
# Return day of the year
dict set date dayOfYear [expr { $day + 1 }]
return $date
}
#----------------------------------------------------------------------
#
# GetMonthDay --
#
# Given the ordinal number of the day within the year, determines
# month and day of month in the Gregorian calendar.
#
# Parameters:
# date - Dictionary containing the date fields. On input, populated
# with the 'era', 'gregorian', 'year' and 'dayOfYear' fields.
#
# Results:
# Returns the given dictionary with the 'month' and 'dayOfMonth'
# fields populated.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::GetMonthDay { date } {
variable DaysInRomanMonthInCommonYear
variable DaysInRomanMonthInLeapYear
set day [dict get $date dayOfYear]
if { [IsGregorianLeapYear $date] } {
set hath $DaysInRomanMonthInLeapYear
} else {
set hath $DaysInRomanMonthInCommonYear
}
set month 1
foreach n $hath {
if { $day <= $n } {
break
}
incr month
incr day [expr { -$n }]
}
dict set date month $month
dict set date dayOfMonth $day
return $date
}
#----------------------------------------------------------------------
#
# GetYearWeekDay
#
# Given a julian day number, fiscal year, fiscal week,
# and day of week in the ISO8601 calendar.
#
# Parameters:
#
# date - Dictionary where the 'julianDay' field is populated.
# daysInFirstWeek - (Optional) Parameter giving the minimum number
# of days in the first week of a year. Default is 4.
#
# Results:
# Returns the given dictionary with values filled in for the
# three given keys.
#
# Side effects:
# None.
#
# Bugs:
# Since ISO8601 week numbering is defined only for the Gregorian
# calendar, dates on the Julian calendar or before the Common
# Era may yield unexpected results. In particular, the year of
# the Julian-to-Gregorian change may be up to three weeks short.
# The era is not managed separately, so if the Common Era begins
# (or the period Before the Common Era ends) with a partial week,
# the few days at the beginning or end of the era may show up
# as incorrectly belonging to the year zero.
#
#----------------------------------------------------------------------
proc ::tcl::clock::GetYearWeekDay { date
{ keys { iso8601Year iso8601Week dayOfWeek } } } {
set daysInFirstWeek 4
set firstDayOfWeek 1
# Determine the calendar year of $j - $daysInFirstWeek + 1.
# Compute an upper bound of the fiscal year as being one year
# past the day on which the current week begins. Find the start
# of that year.
set j [dict get $date julianDay]
set jd [expr { $j - $daysInFirstWeek + 1 }]
set date1 [GetGregorianEraYearDay [dict create julianDay $jd]]
switch -exact -- [dict get $date1 era] {
BCE {
dict set date1 fiscalYear [expr { [dict get $date1 year] - 1}]
}
CE {
dict set date1 fiscalYear [expr { [dict get $date1 year] + 1}]
}
}
dict unset date1 year
dict unset date1 dayOfYear
dict set date1 weekOfFiscalYear 1
dict set date1 dayOfWeek $firstDayOfWeek
set date1 [GetJulianDayFromEraYearWeekDay \
[K $date1 [set date1 {}]] \
$daysInFirstWeek \
$firstDayOfWeek \
{ fiscalYear weekOfFiscalYear dayOfWeek }]
set startOfFiscalYear [dict get $date1 julianDay]
# If we guessed high, move one year earlier.
if { $j < $startOfFiscalYear } {
switch -exact -- [dict get $date1 era] {
BCE {
dict incr date1 fiscalYear
}
CE {
dict incr date1 fiscalYear -1
}
}
set date1 [GetJulianDayFromEraYearWeekDay \
[K $date1 [set date1 {}]] \
$daysInFirstWeek \
$firstDayOfWeek \
{fiscalYear weekOfFiscalYear dayOfWeek }]
set startOfFiscalYear [dict get $date1 julianDay]
}
# Get the week number and the day within the week
set fiscalYear [dict get $date1 fiscalYear]
set dayOfFiscalYear [expr { $j - $startOfFiscalYear }]
set weekOfFiscalYear [expr { ( $dayOfFiscalYear / 7 ) + 1 }]
set dayOfWeek [expr { ( $dayOfFiscalYear + 1 ) % 7 }]
if { $dayOfWeek < $firstDayOfWeek } {
incr dayOfWeek 7
}
# Store the fiscal year, week, and day in the given slots in the
# given dictionary.
foreach key $keys \
value [list $fiscalYear $weekOfFiscalYear $dayOfWeek] {
dict set date $key $value
}
return $date
}
#----------------------------------------------------------------------
#
# GetJulianDayFromEraYearWeekDay --
#
# Finds the Julian Day Number corresponding to the given era,
# year, week and day.
#
# Parameters:
# date -- A dictionary populated with fields whose keys are given
# by the 'keys' parameter below, plus the 'era' field.
# daysInFirstWeek -- (Optional) The minimum number of days in
# the first week of the year. Default is 4.
# firstDayOfWeek -- (Optional) The ordinal number of the first
# day of the week. Default is 1 (Monday);
# 0 (Sunday) is an alternative.
# keys -- (Optional) Keys in the dictionary for looking up the
# fiscal year, fiscal week, and day of week. The
# default is { iso8601Year iso8601Week dayOfWeek }.
#
# Results:
# Returns the dictionary augmented with a 'julianDay' field
# that gives the Julian Day Number corresponding to the given
# date.
#
#----------------------------------------------------------------------
proc ::tcl::clock::GetJulianDayFromEraYearWeekDay {
date
{ daysInFirstWeek 4 }
{ firstDayOfWeek 1 }
{ keys { iso8601Year iso8601Week dayOfWeek } }
} {
foreach var { fiscalYear fiscalWeek dayOfWeek } key $keys {
set $var [dict get $date $key]
}
# Find a day of the first week of the year.
set date2 [dict create \
era [dict get $date era] \
year $fiscalYear \
month 1 \
dayOfMonth $daysInFirstWeek]
set date2 [GetJulianDayFromEraYearMonthDay [K $date2 [set date2 {}]]]
# Find the Julian Day Number of the start of that week.
set jd [WeekdayOnOrBefore $firstDayOfWeek [dict get $date2 julianDay]]
# Add the required number of weeks and days
dict set date julianDay \
[expr { $jd
+ ( 7 * ( $fiscalWeek - 1 ) )
+ $dayOfWeek - $firstDayOfWeek }]
return $date
}
#----------------------------------------------------------------------
#
# GetJulianDayFromEraYearMonthDay --
#
# Given a year, month and day on the Gregorian calendar, determines
# the Julian Day Number beginning at noon on that date.
#
# Parameters:
# date -- A dictionary in which the 'era', 'year', 'month', and
# 'dayOfMonth' slots are populated. The calendar in use
# is determined by the date itself relative to
# [mc GREGORIAN_CHANGE_DATE] in the current locale.
#
# Results:
# Returns the given dictionary augmented with a 'julianDay' key
# whose value is the desired Julian Day Number, and a 'gregorian'
# key that specifies whether the calendar is Gregorian (1) or
# Julian (0).
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::GetJulianDayFromEraYearMonthDay { date } {
variable JD0Jan1CEJul
variable JD0Jan1CEGreg
variable DaysInPriorMonthsInCommonYear
variable DaysInPriorMonthsInLeapYear
# Get absolute year number from the civil year
switch -exact [dict get $date era] {
BCE {
set year [expr { 1 - [dict get $date year] }]
}
CE {
set year [dict get $date year]
}
}
set ym1 [expr { $year - 1 }]
# Try the Gregorian calendar first.
dict set date gregorian 1
set jd [expr { $JD0Jan1CEGreg
+ [dict get $date dayOfMonth]
+ ( [IsGregorianLeapYear $date] ?
[lindex $DaysInPriorMonthsInLeapYear \
[expr { [dict get $date month] - 1}]]
: [lindex $DaysInPriorMonthsInCommonYear \
[expr { [dict get $date month] - 1}]] )
+ ( 365 * $ym1 )
+ ( $ym1 / 4 )
- ( $ym1 / 100 )
+ ( $ym1 / 400 ) }]
# If the date is before the Gregorian change, use the Julian calendar.
if { $jd < [mc GREGORIAN_CHANGE_DATE] } {
dict set date gregorian 0
set jd [expr { $JD0Jan1CEJul
+ [dict get $date dayOfMonth]
+ ( ( $year % 4 == 0 ) ?
[lindex $DaysInPriorMonthsInLeapYear \
[expr { [dict get $date month] - 1}]]
: [lindex $DaysInPriorMonthsInCommonYear \
[expr { [dict get $date month] - 1}]] )
+ ( 365 * $ym1 )
+ ( $ym1 / 4 ) }]
}
dict set date julianDay $jd
return $date
}
#----------------------------------------------------------------------
#
# GetJulianDayFromEraYearDay --
#
# Given a year, month and day on the Gregorian calendar, determines
# the Julian Day Number beginning at noon on that date.
#
# Parameters:
# date -- A dictionary in which the 'era', 'year', and
# 'dayOfYear' slots are populated. The calendar in use
# is determined by the date itself relative to
# [mc GREGORIAN_CHANGE_DATE] in the current locale.
#
# Results:
# Returns the given dictionary augmented with a 'julianDay' key
# whose value is the desired Julian Day Number, and a 'gregorian'
# key that specifies whether the calendar is Gregorian (1) or
# Julian (0).
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::GetJulianDayFromEraYearDay { date } {
variable JD0Jan1CEJul
variable JD0Jan1CEGreg
variable DaysInPriorMonthsInCommonYear
variable DaysInPriorMonthsInLeapYear
# Get absolute year number from the civil year
switch -exact [dict get $date era] {
BCE {
set year [expr { 1 - [dict get $date year] }]
}
CE {
set year [dict get $date year]
}
}
set ym1 [expr { $year - 1 }]
# Try the Gregorian calendar first.
dict set date gregorian 1
set jd [expr { $JD0Jan1CEGreg
+ [dict get $date dayOfYear]
+ ( 365 * $ym1 )
+ ( $ym1 / 4 )
- ( $ym1 / 100 )
+ ( $ym1 / 400 ) }]
# If the date is before the Gregorian change, use the Julian calendar.
if { $jd < [mc GREGORIAN_CHANGE_DATE] } {
dict set date gregorian 0
set jd [expr { $JD0Jan1CEJul
+ [dict get $date dayOfYear]
+ ( 365 * $ym1 )
+ ( $ym1 / 4 ) }]
}
dict set date julianDay $jd
return $date
}
#----------------------------------------------------------------------
#
# GetJulianDayFromEraYearMonthWeekDay --
#
# Determines the Julian Day number corresponding to the nth
# given day-of-the-week in a given month.
#
# Parameters:
# date - Dictionary containing the keys, 'era', 'year', 'month'
# 'weekOfMonth', 'dayOfWeek', and 'dayOfWeekInMonth'.
#
# Results:
# Returns the given dictionary, augmented with a 'julianDay' key.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::GetJulianDayFromEraYearMonthWeekDay { date } {
variable DaysPerWeek
# Come up with a reference day; either the zeroeth day of the
# given month (dayOfWeekInMonth >= 0) or the seventh day of the
# following month (dayOfWeekInMonth < 0)
set date2 $date
set week [dict get $date dayOfWeekInMonth]
if { $week >= 0 } {
dict set date2 dayOfMonth 0
} else {
dict incr date2 month
dict set date2 dayOfMonth 7
}
set date2 [GetJulianDayFromEraYearMonthDay [K $date2 [set date2 {}]]]
set wd0 [WeekdayOnOrBefore [dict get $date dayOfWeek] \
[dict get $date2 julianDay]]
dict set date julianDay [expr { $wd0 + $DaysPerWeek * $week }]
return $date
}
#----------------------------------------------------------------------
#
# IsGregorianLeapYear --
#
# Determines whether a given date represents a leap year in the
# Gregorian calendar.
#
# Parameters:
# date -- The date to test. The fields, 'era', 'year' and 'gregorian'
# must be set.
#
# Results:
# Returns 1 if the year is a leap year, 0 otherwise.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::IsGregorianLeapYear { date } {
switch -exact -- [dict get $date era] {
BCE {
set year [expr { 1 - [dict get $date year]}]
}
CE {
set year [dict get $date year]
}
}
if { $year % 4 != 0 } {
return 0
} elseif { ![dict get $date gregorian] } {
return 1
} elseif { $year % 400 == 0 } {
return 1
} elseif { $year % 100 == 0 } {
return 0
} else {
return 1
}
}
#----------------------------------------------------------------------
#
# WeekdayOnOrBefore --
#
# Determine the nearest day of week (given by the 'weekday'
# parameter, Sunday==0) on or before a given Julian Day.
#
# Parameters:
# weekday -- Day of the week
# j -- Julian Day number
#
# Results:
# Returns the Julian Day Number of the desired date.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::WeekdayOnOrBefore { weekday j } {
set k [expr { ( $weekday + 6 ) % 7 }]
return [expr { $j - ( $j - $k ) % 7 }]
}
#----------------------------------------------------------------------
#
# BSearch --
#
# Service procedure that does binary search in several places
# inside the 'clock' command.
#
# Parameters:
# list - List of lists, sorted in ascending order by the
# first elements
# key - Value to search for
#
# Results:
# Returns the index of the greatest element in $list that is less
# than or equal to $key.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::BSearch { list key } {
if { $key < [lindex $list 0 0] } {
return -1
}
set l 0
set u [expr { [llength $list] - 1 }]
while { $l < $u } {
# At this point, we know that
# $k >= [lindex $list $l 0]
# Either $u == [llength $list] or else $k < [lindex $list $u+1 0]
# We find the midpoint of the interval {l,u} rounded UP, compare
# against it, and set l or u to maintain the invariant. Note
# that the interval shrinks at each step, guaranteeing convergence.
set m [expr { ( $l + $u + 1 ) / 2 }]
if { $key >= [lindex $list $m 0] } {
set l $m
} else {
set u [expr { $m - 1 }]
}
}
return $l
}
#----------------------------------------------------------------------
#
# clock add --
#
# Adds an offset to a given time.
#
# Syntax:
# clock add clockval ?count unit?... ?-option value?
#
# Parameters:
# clockval -- Starting time value
# count -- Amount of a unit of time to add
# unit -- Unit of time to add, must be one of:
# years year months month weeks week
# days day hours hour minutes minute
# seconds second
#
# Options:
# -gmt BOOLEAN
# (Deprecated) Flag synonymous with '-timezone :GMT'
# -timezone ZONE
# Name of the time zone in which calculations are to be done.
# -locale NAME
# Name of the locale in which calculations are to be done.
# Used to determine the Gregorian change date.
#
# Results:
# Returns the given time adjusted by the given offset(s) in
# order.
#
# Notes:
# It is possible that adding a number of months or years will adjust
# the day of the month as well. For instance, the time at
# one month after 31 January is either 28 or 29 February, because
# February has fewer than 31 days.
#
#----------------------------------------------------------------------
proc ::tcl::clock::add { clockval args } {
if { [llength $args] % 2 != 0 } {
return -code error \
-errorcode [list CLOCK wrongNumArgs] \
"wrong \# args: should be\
\"[lindex [info level 0] 0] clockval\
?number units?...\
?-gmt boolean? ?-locale LOCALE? ?-timezone ZONE?\""
}
if { [catch { expr wide($clockval) } result] } {
return -code error $result
}
set offsets {}
set gmt 0
set locale C
set timezone [GetSystemTimeZone]
foreach { a b } $args {
if { [string is integer -strict $a] } {
lappend offsets $a $b
} else {
switch -exact -- $a {
-gmt {
set gmt $b
}
-locale {
set locale $b
}
-timezone {
set timezone $b
}
default {
return -code error \
-errorcode [list CLOCK badSwitch $flag] \
"bad switch \"$flag\",\
must be -gmt, -locale or -timezone"
}
}
}
}
# Check options for validity
if { [info exists saw(-gmt)] && [info exists saw(-timezone)] } {
return -code error \
-errorcode [list CLOCK gmtWithTimezone] \
"cannot use -gmt and -timezone in same call"
}
if { [catch { expr { wide($clockval) } } result] } {
return -code error \
"expected integer but got \"$clockval\""
}
if { ![string is boolean $gmt] } {
return -code error \
"expected boolean value but got \"$gmt\""
} else {
if { $gmt } {
set timezone :GMT
}
}
EnterLocale $locale oldLocale
set status [catch {
foreach { quantity unit } $offsets {
switch -exact -- $unit {
years - year {
set clockval \
[AddMonths [expr { 12 * $quantity }] \
$clockval $timezone]
}
months - month {
set clockval [AddMonths $quantity $clockval $timezone]
}
weeks - week {
set clockval [AddDays [expr { 7 * $quantity }] \
$clockval $timezone]
}
days - day {
set clockval [AddDays $quantity $clockval $timezone]
}
hours - hour {
set clockval [expr { 3600 * $quantity + $clockval }]
}
minutes - minute {
set clockval [expr { 60 * $quantity + $clockval }]
}
seconds - second {
set clockval [expr { $quantity + $clockval }]
}
default {
error "unknown unit \"$unit\", must be \
years, months, weeks, days, hours, minutes or seconds" \
"unknown unit \"$unit\", must be \
years, months, weeks, days, hours, minutes or seconds" \
[list CLOCK badUnit $unit]
}
}
}
} result]
# Restore the locale
if { [info exists oldLocale] } {
mclocale $oldLocale
}
if { $status == 1 } {
if { [lindex $::errorCode 0] eq {CLOCK} } {
return -code error -errorcode $::errorCode $result
} else {
error $result $::errorInfo $::errorCode
}
} else {
return $clockval
}
}
#----------------------------------------------------------------------
#
# AddMonths --
#
# Add a given number of months to a given clock value in a given
# time zone.
#
# Parameters:
# months - Number of months to add (may be negative)
# clockval - Seconds since the epoch before the operation
# timezone - Time zone in which the operation is to be performed
#
# Results:
# Returns the new clock value as a number of seconds since
# the epoch.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::AddMonths { months clockval timezone } {
variable DaysInRomanMonthInCommonYear
variable DaysInRomanMonthInLeapYear
variable PosixEpochAsJulianSeconds
variable SecondsPerDay
# Convert the time to year, month, day, and fraction of day.
set date [GetMonthDay \
[GetGregorianEraYearDay \
[GetJulianDay \
[ConvertUTCToLocal \
[dict create seconds $clockval] \
$timezone]]]]
dict set date secondOfDay [expr { [dict get $date localSeconds]
% $SecondsPerDay }]
dict set date tzName $timezone
# Add the requisite number of months
set m [dict get $date month]
incr m $months
incr m -1
set delta [expr { $m / 12 }]
set mm [expr { $m % 12 }]
dict set date month [expr { $mm + 1 }]
dict incr date year $delta
# If the date doesn't exist in the current month, repair it
if { [IsGregorianLeapYear $date] } {
set hath [lindex $DaysInRomanMonthInLeapYear $mm]
} else {
set hath [lindex $DaysInRomanMonthInCommonYear $mm]
}
if { [dict get $date dayOfMonth] > $hath } {
dict set date dayOfMonth $hath
}
# Reconvert to a number of seconds
set date [GetJulianDayFromEraYearMonthDay \
[K $date [set date {}]]]
dict set date localSeconds \
[expr { -$PosixEpochAsJulianSeconds
+ ( $SecondsPerDay * wide([dict get $date julianDay]) )
+ [dict get $date secondOfDay] }]
set date [ConvertLocalToUTC [K $date [set date {}]]]
return [dict get $date seconds]
}
#----------------------------------------------------------------------
#
# AddDays --
#
# Add a given number of days to a given clock value in a given
# time zone.
#
# Parameters:
# days - Number of days to add (may be negative)
# clockval - Seconds since the epoch before the operation
# timezone - Time zone in which the operation is to be performed
#
# Results:
# Returns the new clock value as a number of seconds since
# the epoch.
#
# Side effects:
# None.
#
#----------------------------------------------------------------------
proc ::tcl::clock::AddDays { days clockval timezone } {
variable PosixEpochAsJulianSeconds
variable SecondsPerDay
# Convert the time to Julian Day
set date [GetJulianDay \
[ConvertUTCToLocal \
[dict create seconds $clockval] \
$timezone]]
dict set date secondOfDay [expr { [dict get $date localSeconds]
% $SecondsPerDay }]
dict set date tzName $timezone
# Add the requisite number of days
dict incr date julianDay $days
# Reconvert to a number of seconds
dict set date localSeconds \
[expr { -$PosixEpochAsJulianSeconds
+ ( $SecondsPerDay * wide([dict get $date julianDay]) )
+ [dict get $date secondOfDay] }]
set date [ConvertLocalToUTC [K $date [set date {}]]]
return [dict get $date seconds]
}
#----------------------------------------------------------------------
#
# ClearCaches --
#
# Clears all caches to reclaim the memory used in [clock]
#
# Parameters:
# None.
#
# Results:
# None.
#
# Side effects:
# Caches are cleared.
#
#----------------------------------------------------------------------
proc ::tcl::clock::ClearCaches {} {
variable LocaleNumeralCache
variable McLoaded
variable CachedSystemTimeZone
variable TZData
foreach p [info procs [namespace current]::scanproc'*] {
rename $p {}
}
set LocaleNumeralCache {}
set McLoaded {}
catch {unset CachedSystemTimeZone}
initTZData
}
|