summaryrefslogtreecommitdiffstats
path: root/src/corelib/time/qdatetime.cpp
blob: cde8587094430e4a3dc8ebaa97e1d1b275466ab0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
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
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
/****************************************************************************
**
** Copyright (C) 2019 The Qt Company Ltd.
** Copyright (C) 2016 Intel Corporation.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qplatformdefs.h"
#include "private/qdatetime_p.h"
#if QT_CONFIG(datetimeparser)
#include "private/qdatetimeparser_p.h"
#endif

#include "qdatastream.h"
#include "qset.h"
#include "qlocale.h"
#include "qdatetime.h"
#if QT_CONFIG(timezone)
#include "qtimezoneprivate_p.h"
#endif
#include "qregexp.h"
#include "qdebug.h"
#ifndef Q_OS_WIN
#include <locale.h>
#endif

#include <cmath>
#ifdef Q_CC_MINGW
#  include <unistd.h> // Define _POSIX_THREAD_SAFE_FUNCTIONS to obtain localtime_r()
#endif
#include <time.h>
#ifdef Q_OS_WIN
#  include <qt_windows.h>
#  ifdef Q_OS_WINRT
#    include "qfunctions_winrt.h"
#  endif
#endif

#if defined(Q_OS_MAC)
#include <private/qcore_mac_p.h>
#endif

#include "qcalendar.h"
#include "qgregoriancalendar_p.h"

QT_BEGIN_NAMESPACE

/*****************************************************************************
  Date/Time Constants
 *****************************************************************************/

enum {
    SECS_PER_DAY = 86400,
    MSECS_PER_DAY = 86400000,
    SECS_PER_HOUR = 3600,
    MSECS_PER_HOUR = 3600000,
    SECS_PER_MIN = 60,
    MSECS_PER_MIN = 60000,
    TIME_T_MAX = 2145916799,  // int maximum 2037-12-31T23:59:59 UTC
    JULIAN_DAY_FOR_EPOCH = 2440588 // result of julianDayFromDate(1970, 1, 1)
};

/*****************************************************************************
  QDate static helper functions
 *****************************************************************************/

static inline QDate fixedDate(QCalendar::YearMonthDay &&parts, QCalendar cal)
{
    if ((parts.year < 0 && !cal.isProleptic()) || (parts.year == 0 && !cal.hasYearZero()))
        return QDate();

    parts.day = qMin(parts.day, cal.daysInMonth(parts.month, parts.year));
    return cal.dateFromParts(parts);
}

static inline QDate fixedDate(QCalendar::YearMonthDay &&parts)
{
    if (parts.year) {
        parts.day = qMin(parts.day, QGregorianCalendar::monthLength(parts.month, parts.year));
        qint64 jd;
        if (QGregorianCalendar::julianFromParts(parts.year, parts.month, parts.day, &jd))
            return QDate::fromJulianDay(jd);
    }
    return QDate();
}

/*****************************************************************************
  Date/Time formatting helper functions
 *****************************************************************************/

#if QT_CONFIG(textdate)
static const char qt_shortMonthNames[][4] = {
    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

static int qt_monthNumberFromShortName(QStringView shortName)
{
    for (unsigned int i = 0; i < sizeof(qt_shortMonthNames) / sizeof(qt_shortMonthNames[0]); ++i) {
        if (shortName == QLatin1String(qt_shortMonthNames[i], 3))
            return i + 1;
    }
    return -1;
}
static int qt_monthNumberFromShortName(const QString &shortName)
{ return qt_monthNumberFromShortName(QStringView(shortName)); }

static int fromShortMonthName(QStringView monthName, int year)
{
    // Assume that English monthnames are the default
    int month = qt_monthNumberFromShortName(monthName);
    if (month != -1)
        return month;
    // If English names can't be found, search the localized ones
    for (int i = 1; i <= 12; ++i) {
        if (monthName == QCalendar().monthName(QLocale::system(), i, year, QLocale::ShortFormat))
            return i;
    }
    return -1;
}
#endif // textdate

#if QT_CONFIG(datestring)
struct ParsedRfcDateTime {
    QDate date;
    QTime time;
    int utcOffset;
};

static ParsedRfcDateTime rfcDateImpl(const QString &s)
{
    ParsedRfcDateTime result;

    // Matches "[ddd,] dd MMM yyyy[ hh:mm[:ss]] [±hhmm]" - correct RFC 822, 2822, 5322 format
    QRegExp rex(QStringLiteral("^[ \\t]*(?:[A-Z][a-z]+,)?[ \\t]*(\\d{1,2})[ \\t]+([A-Z][a-z]+)[ \\t]+(\\d\\d\\d\\d)(?:[ \\t]+(\\d\\d):(\\d\\d)(?::(\\d\\d))?)?[ \\t]*(?:([+-])(\\d\\d)(\\d\\d))?"));
    if (s.indexOf(rex) == 0) {
        const QStringList cap = rex.capturedTexts();
        result.date = QDate(cap[3].toInt(), qt_monthNumberFromShortName(cap[2]), cap[1].toInt());
        if (!cap[4].isEmpty())
            result.time = QTime(cap[4].toInt(), cap[5].toInt(), cap[6].toInt());
        const bool positiveOffset = (cap[7] == QLatin1String("+"));
        const int hourOffset = cap[8].toInt();
        const int minOffset = cap[9].toInt();
        result.utcOffset = ((hourOffset * 60 + minOffset) * (positiveOffset ? 60 : -60));
    } else {
        // Matches "ddd MMM dd[ hh:mm:ss] yyyy [±hhmm]" - permissive RFC 850, 1036 (read only)
        QRegExp rex(QStringLiteral("^[ \\t]*[A-Z][a-z]+[ \\t]+([A-Z][a-z]+)[ \\t]+(\\d\\d)(?:[ \\t]+(\\d\\d):(\\d\\d):(\\d\\d))?[ \\t]+(\\d\\d\\d\\d)[ \\t]*(?:([+-])(\\d\\d)(\\d\\d))?"));
        if (s.indexOf(rex) == 0) {
            const QStringList cap = rex.capturedTexts();
            result.date = QDate(cap[6].toInt(), qt_monthNumberFromShortName(cap[1]), cap[2].toInt());
            if (!cap[3].isEmpty())
                result.time = QTime(cap[3].toInt(), cap[4].toInt(), cap[5].toInt());
            const bool positiveOffset = (cap[7] == QLatin1String("+"));
            const int hourOffset = cap[8].toInt();
            const int minOffset = cap[9].toInt();
            result.utcOffset = ((hourOffset * 60 + minOffset) * (positiveOffset ? 60 : -60));
        }
    }

    return result;
}
#endif // datestring

// Return offset in [+-]HH:mm format
static QString toOffsetString(Qt::DateFormat format, int offset)
{
    return QString::asprintf("%c%02d%s%02d",
                             offset >= 0 ? '+' : '-',
                             qAbs(offset) / SECS_PER_HOUR,
                             // Qt::ISODate puts : between the hours and minutes, but Qt:TextDate does not:
                             format == Qt::TextDate ? "" : ":",
                             (qAbs(offset) / 60) % 60);
}

#if QT_CONFIG(datestring)
// Parse offset in [+-]HH[[:]mm] format
static int fromOffsetString(QStringView offsetString, bool *valid) noexcept
{
    *valid = false;

    const int size = offsetString.size();
    if (size < 2 || size > 6)
        return 0;

    // sign will be +1 for a positive and -1 for a negative offset
    int sign;

    // First char must be + or -
    const QChar signChar = offsetString.at(0);
    if (signChar == QLatin1Char('+'))
        sign = 1;
    else if (signChar == QLatin1Char('-'))
        sign = -1;
    else
        return 0;

    // Split the hour and minute parts
    const QStringView time = offsetString.mid(1);
    qsizetype hhLen = time.indexOf(QLatin1Char(':'));
    qsizetype mmIndex;
    if (hhLen == -1)
        mmIndex = hhLen = 2; // [+-]HHmm or [+-]HH format
    else
        mmIndex = hhLen + 1;

    const QLocale C = QLocale::c();
    const QStringView hhRef = time.left(qMin(hhLen, time.size()));
    bool ok = false;
    const int hour = C.toInt(hhRef, &ok);
    if (!ok)
        return 0;

    const QStringView mmRef = time.mid(qMin(mmIndex, time.size()));
    const int minute = mmRef.isEmpty() ? 0 : C.toInt(mmRef, &ok);
    if (!ok || minute < 0 || minute > 59)
        return 0;

    *valid = true;
    return sign * ((hour * 60) + minute) * 60;
}
#endif // datestring

/*****************************************************************************
  QDate member functions
 *****************************************************************************/

/*!
    \since 4.5

    \enum QDate::MonthNameType

    This enum describes the types of the string representation used
    for the month name.

    \value DateFormat This type of name can be used for date-to-string formatting.
    \value StandaloneFormat This type is used when you need to enumerate months or weekdays.
           Usually standalone names are represented in singular forms with
           capitalized first letter.
*/

/*!
    \class QDate
    \inmodule QtCore
    \reentrant
    \brief The QDate class provides date functions.


    A QDate object represents a particular date. This can be expressed as a
    calendar date, i.e. year, month, and day numbers, in the proleptic Gregorian
    calendar.

    A QDate object is typically created by giving the year, month, and day
    numbers explicitly. Note that QDate interprets year numbers less than 100 as
    presented, i.e., as years 1 through 99, without adding any offset. The
    static function currentDate() creates a QDate object containing the date
    read from the system clock. An explicit date can also be set using
    setDate(). The fromString() function returns a QDate given a string and a
    date format which is used to interpret the date within the string.

    The year(), month(), and day() functions provide access to the year, month,
    and day numbers. Also, dayOfWeek() and dayOfYear() functions are
    provided. The same information is provided in textual format by
    toString(). The day and month numbers can be mapped to names using QLocale.

    QDate provides a full set of operators to compare two QDate
    objects where smaller means earlier, and larger means later.

    You can increment (or decrement) a date by a given number of days
    using addDays(). Similarly you can use addMonths() and addYears().
    The daysTo() function returns the number of days between two
    dates.

    The daysInMonth() and daysInYear() functions return how many days
    there are in this date's month and year, respectively. The
    isLeapYear() function indicates whether a date is in a leap year.

    \section1 Remarks

    \section2 No Year 0

    There is no year 0. Dates in that year are considered invalid. The year -1
    is the year "1 before Christ" or "1 before current era." The day before 1
    January 1 CE, QDate(1, 1, 1), is 31 December 1 BCE, QDate(-1, 12, 31).

    \section2 Range of Valid Dates

    Dates are stored internally as a Julian Day number, an integer count of
    every day in a contiguous range, with 24 November 4714 BCE in the Gregorian
    calendar being Julian Day 0 (1 January 4713 BCE in the Julian calendar).
    As well as being an efficient and accurate way of storing an absolute date,
    it is suitable for converting a date into other calendar systems such as
    Hebrew, Islamic or Chinese. The Julian Day number can be obtained using
    QDate::toJulianDay() and can be set using QDate::fromJulianDay().

    The range of dates able to be stored by QDate as a Julian Day number is
    for technical reasons limited to between -784350574879 and 784354017364,
    which means from before 2 billion BCE to after 2 billion CE.

    \sa QTime, QDateTime, QCalendar, QDateTime::YearRange, QDateEdit, QDateTimeEdit, QCalendarWidget
*/

/*!
    \fn QDate::QDate()

    Constructs a null date. Null dates are invalid.

    \sa isNull(), isValid()
*/

/*!
    Constructs a date with year \a y, month \a m and day \a d.

    The date is understood in terms of the Gregorian calendar. If the specified
    date is invalid, the date is not set and isValid() returns \c false.

    \warning Years 1 to 99 are interpreted as is. Year 0 is invalid.

    \sa isValid(), QCalendar::dateFromParts()
*/

QDate::QDate(int y, int m, int d)
{
    if (!QGregorianCalendar::julianFromParts(y, m, d, &jd))
        jd = nullJd();
}

QDate::QDate(int y, int m, int d, QCalendar cal)
{
    *this = cal.dateFromParts(y, m, d);
}

/*!
    \fn bool QDate::isNull() const

    Returns \c true if the date is null; otherwise returns \c false. A null
    date is invalid.

    \note The behavior of this function is equivalent to isValid().

    \sa isValid()
*/

/*!
    \fn bool QDate::isValid() const

    Returns \c true if this date is valid; otherwise returns \c false.

    \sa isNull(), QCalendar::isDateValid()
*/

/*!
    Returns the year of this date.

    Uses \a cal as calendar, if supplied, else the Gregorian calendar.

    Returns 0 if the date is invalid. For some calendars, dates before their
    first year may all be invalid.

    If using a calendar which has a year 0, check using isValid() if the return
    is 0. Such calendars use negative year numbers in the obvious way, with
    year 1 preceded by year 0, in turn preceded by year -1 and so on.

    Some calendars, despite having no year 0, have a conventional numbering of
    the years before their first year, counting backwards from 1. For example,
    in the proleptic Gregorian calendar, successive years before 1 CE (the first
    year) are identified as 1 BCE, 2 BCE, 3 BCE and so on. For such calendars,
    negative year numbers are used to indicate these years before year 1, with
    -1 indicating the year before 1.

    \sa month(), day(), QCalendar::hasYearZero(), QCalendar::isProleptic()
*/

int QDate::year(QCalendar cal) const
{
    if (isValid()) {
        const auto parts = cal.partsFromDate(*this);
        if (parts.isValid())
            return parts.year;
    }
    return 0;
}

/*!
  \overload
 */

int QDate::year() const
{
    if (isValid()) {
        const auto parts = QGregorianCalendar::partsFromJulian(jd);
        if (parts.isValid())
            return parts.year;
    }
    return 0;
}

/*!
    Returns the month-number for the date.

    Numbers the months of the year starting with 1 for the first. Uses \a cal
    as calendar if supplied, else the Gregorian calendar, for which the month
    numbering is as follows:

    \list
    \li 1 = "January"
    \li 2 = "February"
    \li 3 = "March"
    \li 4 = "April"
    \li 5 = "May"
    \li 6 = "June"
    \li 7 = "July"
    \li 8 = "August"
    \li 9 = "September"
    \li 10 = "October"
    \li 11 = "November"
    \li 12 = "December"
    \endlist

    Returns 0 if the date is invalid. Note that some calendars may have more
    than 12 months in some years.

    \sa year(), day()
*/

int QDate::month(QCalendar cal) const
{
    if (isValid()) {
        const auto parts = cal.partsFromDate(*this);
        if (parts.isValid())
            return parts.month;
    }
    return 0;
}

/*!
  \overload
 */

int QDate::month() const
{
    if (isValid()) {
        const auto parts = QGregorianCalendar::partsFromJulian(jd);
        if (parts.isValid())
            return parts.month;
    }
    return 0;
}

/*!
    Returns the day of the month for this date.

    Uses \a cal as calendar if supplied, else the Gregorian calendar (for which
    the return ranges from 1 to 31). Returns 0 if the date is invalid.

    \sa year(), month(), dayOfWeek()
*/

int QDate::day(QCalendar cal) const
{
    if (isValid()) {
        const auto parts = cal.partsFromDate(*this);
        if (parts.isValid())
            return parts.day;
    }
    return 0;
}

/*!
  \overload
 */

int QDate::day() const
{
    if (isValid()) {
        const auto parts = QGregorianCalendar::partsFromJulian(jd);
        if (parts.isValid())
            return parts.day;
    }
    return 0;
}

/*!
    Returns the weekday (1 = Monday to 7 = Sunday) for this date.

    Uses \a cal as calendar if supplied, else the Gregorian calendar. Returns 0
    if the date is invalid. Some calendars may give special meaning
    (e.g. intercallary days) to values greater than 7.

    \sa day(), dayOfYear(), Qt::DayOfWeek
*/

int QDate::dayOfWeek(QCalendar cal) const
{
    if (isNull())
        return 0;

    return cal.dayOfWeek(*this);
}

/*!
  \overload
 */

int QDate::dayOfWeek() const
{
    return isValid() ? QGregorianCalendar::weekDayOfJulian(jd) : 0;
}

/*!
    Returns the day of the year (1 for the first day) for this date.

    Uses \a cal as calendar if supplied, else the Gregorian calendar.
    Returns 0 if either the date or the first day of its year is invalid.

    \sa day(), dayOfWeek()
*/

int QDate::dayOfYear(QCalendar cal) const
{
    if (isValid()) {
        QDate firstDay = cal.dateFromParts(year(cal), 1, 1);
        if (firstDay.isValid())
            return firstDay.daysTo(*this) + 1;
    }
    return 0;
}

/*!
  \overload
 */

int QDate::dayOfYear() const
{
    if (isValid()) {
        qint64 first;
        if (QGregorianCalendar::julianFromParts(year(), 1, 1, &first))
            return jd - first + 1;
    }
    return 0;
}

/*!
    Returns the number of days in the month for this date.

    Uses \a cal as calendar if supplied, else the Gregorian calendar (for which
    the result ranges from 28 to 31). Returns 0 if the date is invalid.

    \sa day(), daysInYear()
*/

int QDate::daysInMonth(QCalendar cal) const
{
    if (isValid()) {
        const auto parts = cal.partsFromDate(*this);
        if (parts.isValid())
            return cal.daysInMonth(parts.month, parts.year);
    }
    return 0;
}

/*!
  \overload
 */

int QDate::daysInMonth() const
{
    if (isValid()) {
        const auto parts = QGregorianCalendar::partsFromJulian(jd);
        if (parts.isValid())
            return QGregorianCalendar::monthLength(parts.month, parts.year);
    }
    return 0;
}

/*!
    Returns the number of days in the year for this date.

    Uses \a cal as calendar if supplied, else the Gregorian calendar (for which
    the result is 365 or 366). Returns 0 if the date is invalid.

    \sa day(), daysInMonth()
*/

int QDate::daysInYear(QCalendar cal) const
{
    if (isNull())
        return 0;

    return cal.daysInYear(year(cal));
}

/*!
  \overload
 */

int QDate::daysInYear() const
{
    return isValid() ? QGregorianCalendar::leapTest(year()) ? 366 : 365 : 0;
}

/*!
    Returns the ISO 8601 week number (1 to 53).

    Returns 0 if the date is invalid. Otherwise, returns the week number for the
    date. If \a yearNumber is not \nullptr (its default), stores the year as
    *\a{yearNumber}.

    In accordance with ISO 8601, each week falls in the year to which most of
    its days belong, in the Gregorian calendar. As ISO 8601's week starts on
    Monday, this is the year in which the week's Thursday falls. Most years have
    52 weeks, but some have 53.

    \note *\a{yearNumber} is not always the same as year(). For example, 1
    January 2000 has week number 52 in the year 1999, and 31 December
    2002 has week number 1 in the year 2003.

    \sa isValid()
*/

int QDate::weekNumber(int *yearNumber) const
{
    if (!isValid())
        return 0;

    // This could be replaced by use of QIso8601Calendar, once we implement it.
    // The Thursday of the same week determines our answer:
    QDate thursday(addDays(4 - dayOfWeek()));
    int year = thursday.year();
    // Week n's Thurs's DOY has 1 <= DOY - 7*(n-1) < 8, so 0 <= DOY + 6 - 7*n < 7:
    int week = (thursday.dayOfYear() + 6) / 7;

    if (yearNumber)
        *yearNumber = year;
    return week;
}

static bool inDateTimeRange(qint64 jd, bool start)
{
    using Bounds = std::numeric_limits<qint64>;
    if (jd < Bounds::min() + JULIAN_DAY_FOR_EPOCH)
        return false;
    jd -= JULIAN_DAY_FOR_EPOCH;
    const qint64 maxDay = Bounds::max() / MSECS_PER_DAY;
    const qint64 minDay = Bounds::min() / MSECS_PER_DAY - 1;
    // (Divisions rounded towards zero, as MSECS_PER_DAY has factors other than two.)
    // Range includes start of last day and end of first:
    if (start)
        return jd > minDay && jd <= maxDay;
    return jd >= minDay && jd < maxDay;
}

static QDateTime toEarliest(const QDate &day, const QDateTime &form)
{
    const Qt::TimeSpec spec = form.timeSpec();
    const int offset = (spec == Qt::OffsetFromUTC) ? form.offsetFromUtc() : 0;
#if QT_CONFIG(timezone)
    QTimeZone zone;
    if (spec == Qt::TimeZone)
        zone = form.timeZone();
#endif
    auto moment = [=](QTime time) {
        switch (spec) {
        case Qt::OffsetFromUTC: return QDateTime(day, time, spec, offset);
#if QT_CONFIG(timezone)
        case Qt::TimeZone: return QDateTime(day, time, zone);
#endif
        default: return QDateTime(day, time, spec);
        }
    };
    // Longest routine time-zone transition is 2 hours:
    QDateTime when = moment(QTime(2, 0));
    if (!when.isValid()) {
        // Noon should be safe ...
        when = moment(QTime(12, 0));
        if (!when.isValid()) {
            // ... unless it's a 24-hour jump (moving the date-line)
            when = moment(QTime(23, 59, 59, 999));
            if (!when.isValid())
                return QDateTime();
        }
    }
    int high = when.time().msecsSinceStartOfDay() / 60000;
    int low = 0;
    // Binary chop to the right minute
    while (high > low + 1) {
        int mid = (high + low) / 2;
        QDateTime probe = moment(QTime(mid / 60, mid % 60));
        if (probe.isValid() && probe.date() == day) {
            high = mid;
            when = probe;
        } else {
            low = mid;
        }
    }
    return when;
}

/*!
    \since 5.14
    \fn QDateTime QDate::startOfDay(Qt::TimeSpec spec, int offsetSeconds) const
    \fn QDateTime QDate::startOfDay(const QTimeZone &zone) const

    Returns the start-moment of the day.  Usually, this shall be midnight at the
    start of the day: however, if a time-zone transition causes the given date
    to skip over that midnight (e.g. a DST spring-forward skipping from the end
    of the previous day to 01:00 of the new day), the actual earliest time in
    the day is returned.  This can only arise when the start-moment is specified
    in terms of a time-zone (by passing its QTimeZone as \a zone) or in terms of
    local time (by passing Qt::LocalTime as \a spec; this is its default).

    The \a offsetSeconds is ignored unless \a spec is Qt::OffsetFromUTC, when it
    gives the implied zone's offset from UTC.  As UTC and such zones have no
    transitions, the start of the day is QTime(0, 0) in these cases.

    In the rare case of a date that was entirely skipped (this happens when a
    zone east of the international date-line switches to being west of it), the
    return shall be invalid.  Passing Qt::TimeZone as \a spec (instead of
    passing a QTimeZone) or passing an invalid time-zone as \a zone will also
    produce an invalid result, as shall dates that start outside the range
    representable by QDateTime.

    \sa endOfDay()
*/
QDateTime QDate::startOfDay(Qt::TimeSpec spec, int offsetSeconds) const
{
    if (!inDateTimeRange(jd, true))
        return QDateTime();

    switch (spec) {
    case Qt::TimeZone: // should pass a QTimeZone instead of Qt::TimeZone
        qWarning() << "Called QDate::startOfDay(Qt::TimeZone) on" << *this;
        return QDateTime();
    case Qt::OffsetFromUTC:
    case Qt::UTC:
        return QDateTime(*this, QTime(0, 0), spec, offsetSeconds);

    case Qt::LocalTime:
        if (offsetSeconds)
            qWarning("Ignoring offset (%d seconds) passed with Qt::LocalTime", offsetSeconds);
        break;
    }
    QDateTime when(*this, QTime(0, 0), spec);
    if (!when.isValid())
        when = toEarliest(*this, when);

    return when.isValid() ? when : QDateTime();
}

#if QT_CONFIG(timezone)
/*!
  \overload
  \since 5.14
*/
QDateTime QDate::startOfDay(const QTimeZone &zone) const
{
    if (!inDateTimeRange(jd, true) || !zone.isValid())
        return QDateTime();

    QDateTime when(*this, QTime(0, 0), zone);
    if (when.isValid())
        return when;

    // The start of the day must have fallen in a spring-forward's gap; find the spring-forward:
    if (zone.hasTransitions()) {
        QTimeZone::OffsetData tran = zone.previousTransition(QDateTime(*this, QTime(23, 59, 59, 999), zone));
        const QDateTime &at = tran.atUtc.toTimeZone(zone);
        if (at.isValid() && at.date() == *this)
            return at;
    }

    when = toEarliest(*this, when);
    return when.isValid() ? when : QDateTime();
}
#endif // timezone

static QDateTime toLatest(const QDate &day, const QDateTime &form)
{
    const Qt::TimeSpec spec = form.timeSpec();
    const int offset = (spec == Qt::OffsetFromUTC) ? form.offsetFromUtc() : 0;
#if QT_CONFIG(timezone)
    QTimeZone zone;
    if (spec == Qt::TimeZone)
        zone = form.timeZone();
#endif
    auto moment = [=](QTime time) {
        switch (spec) {
        case Qt::OffsetFromUTC: return QDateTime(day, time, spec, offset);
#if QT_CONFIG(timezone)
        case Qt::TimeZone: return QDateTime(day, time, zone);
#endif
        default: return QDateTime(day, time, spec);
        }
    };
    // Longest routine time-zone transition is 2 hours:
    QDateTime when = moment(QTime(21, 59, 59, 999));
    if (!when.isValid()) {
        // Noon should be safe ...
        when = moment(QTime(12, 0));
        if (!when.isValid()) {
            // ... unless it's a 24-hour jump (moving the date-line)
            when = moment(QTime(0, 0));
            if (!when.isValid())
                return QDateTime();
        }
    }
    int high = 24 * 60;
    int low = when.time().msecsSinceStartOfDay() / 60000;
    // Binary chop to the right minute
    while (high > low + 1) {
        int mid = (high + low) / 2;
        QDateTime probe = moment(QTime(mid / 60, mid % 60, 59, 999));
        if (probe.isValid() && probe.date() == day) {
            low = mid;
            when = probe;
        } else {
            high = mid;
        }
    }
    return when;
}

/*!
    \since 5.14
    \fn QDateTime QDate::endOfDay(Qt::TimeSpec spec, int offsetSeconds) const
    \fn QDateTime QDate::endOfDay(const QTimeZone &zone) const

    Returns the end-moment of the day.  Usually, this is one millisecond before
    the midnight at the end of the day: however, if a time-zone transition
    causes the given date to skip over that midnight (e.g. a DST spring-forward
    skipping from just before 23:00 to the start of the next day), the actual
    latest time in the day is returned.  This can only arise when the
    start-moment is specified in terms of a time-zone (by passing its QTimeZone
    as \a zone) or in terms of local time (by passing Qt::LocalTime as \a spec;
    this is its default).

    The \a offsetSeconds is ignored unless \a spec is Qt::OffsetFromUTC, when it
    gives the implied zone's offset from UTC.  As UTC and such zones have no
    transitions, the end of the day is QTime(23, 59, 59, 999) in these cases.

    In the rare case of a date that was entirely skipped (this happens when a
    zone east of the international date-line switches to being west of it), the
    return shall be invalid.  Passing Qt::TimeZone as \a spec (instead of
    passing a QTimeZone) will also produce an invalid result, as shall dates
    that end outside the range representable by QDateTime.

    \sa startOfDay()
*/
QDateTime QDate::endOfDay(Qt::TimeSpec spec, int offsetSeconds) const
{
    if (!inDateTimeRange(jd, false))
        return QDateTime();

    switch (spec) {
    case Qt::TimeZone: // should pass a QTimeZone instead of Qt::TimeZone
        qWarning() << "Called QDate::endOfDay(Qt::TimeZone) on" << *this;
        return QDateTime();
    case Qt::UTC:
    case Qt::OffsetFromUTC:
        return QDateTime(*this, QTime(23, 59, 59, 999), spec, offsetSeconds);

    case Qt::LocalTime:
        if (offsetSeconds)
            qWarning("Ignoring offset (%d seconds) passed with Qt::LocalTime", offsetSeconds);
        break;
    }
    QDateTime when(*this, QTime(23, 59, 59, 999), spec);
    if (!when.isValid())
        when = toLatest(*this, when);
    return when.isValid() ? when : QDateTime();
}

#if QT_CONFIG(timezone)
/*!
  \overload
  \since 5.14
*/
QDateTime QDate::endOfDay(const QTimeZone &zone) const
{
    if (!inDateTimeRange(jd, false) || !zone.isValid())
        return QDateTime();

    QDateTime when(*this, QTime(23, 59, 59, 999), zone);
    if (when.isValid())
        return when;

    // The end of the day must have fallen in a spring-forward's gap; find the spring-forward:
    if (zone.hasTransitions()) {
        QTimeZone::OffsetData tran = zone.nextTransition(QDateTime(*this, QTime(0, 0), zone));
        const QDateTime &at = tran.atUtc.toTimeZone(zone);
        if (at.isValid() && at.date() == *this)
            return at;
    }

    when = toLatest(*this, when);
    return when.isValid() ? when : QDateTime();
}
#endif // timezone

#if QT_DEPRECATED_SINCE(5, 11) && QT_CONFIG(textdate)

/*!
    \since 4.5
    \deprecated

    Returns the short name of the \a month for the representation specified
    by \a type.

    The months are enumerated using the following convention:

    \list
    \li 1 = "Jan"
    \li 2 = "Feb"
    \li 3 = "Mar"
    \li 4 = "Apr"
    \li 5 = "May"
    \li 6 = "Jun"
    \li 7 = "Jul"
    \li 8 = "Aug"
    \li 9 = "Sep"
    \li 10 = "Oct"
    \li 11 = "Nov"
    \li 12 = "Dec"
    \endlist

    The month names will be localized according to the system's
    locale settings, i.e. using QLocale::system().

    Returns an empty string if the date is invalid.

    \sa toString(), longMonthName(), shortDayName(), longDayName()
*/

QString QDate::shortMonthName(int month, QDate::MonthNameType type)
{
    switch (type) {
    case QDate::DateFormat:
        return QCalendar().monthName(QLocale::system(), month,
                                     QCalendar::Unspecified, QLocale::ShortFormat);
    case QDate::StandaloneFormat:
        return QCalendar().standaloneMonthName(QLocale::system(), month,
                                               QCalendar::Unspecified, QLocale::ShortFormat);
    }
    return QString();
}

/*!
    \since 4.5
    \deprecated

    Returns the long name of the \a month for the representation specified
    by \a type.

    The months are enumerated using the following convention:

    \list
    \li 1 = "January"
    \li 2 = "February"
    \li 3 = "March"
    \li 4 = "April"
    \li 5 = "May"
    \li 6 = "June"
    \li 7 = "July"
    \li 8 = "August"
    \li 9 = "September"
    \li 10 = "October"
    \li 11 = "November"
    \li 12 = "December"
    \endlist

    The month names will be localized according to the system's
    locale settings, i.e. using QLocale::system().

    Returns an empty string if the date is invalid.

    \sa toString(), shortMonthName(), shortDayName(), longDayName()
*/

QString QDate::longMonthName(int month, MonthNameType type)
{
    switch (type) {
    case QDate::DateFormat:
        return QCalendar().monthName(QLocale::system(), month,
                                     QCalendar::Unspecified, QLocale::LongFormat);
    case QDate::StandaloneFormat:
        return QCalendar().standaloneMonthName(QLocale::system(), month,
                                               QCalendar::Unspecified, QLocale::LongFormat);
    }
    return QString();
}

/*!
    \since 4.5
    \deprecated

    Returns the short name of the \a weekday for the representation specified
    by \a type.

    The days are enumerated using the following convention:

    \list
    \li 1 = "Mon"
    \li 2 = "Tue"
    \li 3 = "Wed"
    \li 4 = "Thu"
    \li 5 = "Fri"
    \li 6 = "Sat"
    \li 7 = "Sun"
    \endlist

    The day names will be localized according to the system's
    locale settings, i.e. using QLocale::system().

    Returns an empty string if the date is invalid.

    \sa toString(), shortMonthName(), longMonthName(), longDayName()
*/

QString QDate::shortDayName(int weekday, MonthNameType type)
{
    switch (type) {
    case QDate::DateFormat:
        return QLocale::system().dayName(weekday, QLocale::ShortFormat);
    case QDate::StandaloneFormat:
        return QLocale::system().standaloneDayName(weekday, QLocale::ShortFormat);
    }
    return QString();
}

/*!
    \since 4.5
    \deprecated

    Returns the long name of the \a weekday for the representation specified
    by \a type.

    The days are enumerated using the following convention:

    \list
    \li 1 = "Monday"
    \li 2 = "Tuesday"
    \li 3 = "Wednesday"
    \li 4 = "Thursday"
    \li 5 = "Friday"
    \li 6 = "Saturday"
    \li 7 = "Sunday"
    \endlist

    The day names will be localized according to the system's
    locale settings, i.e. using QLocale::system().

    Returns an empty string if the date is invalid.

    \sa toString(), shortDayName(), shortMonthName(), longMonthName()
*/

QString QDate::longDayName(int weekday, MonthNameType type)
{
    switch (type) {
    case QDate::DateFormat:
        return QLocale::system().dayName(weekday, QLocale::LongFormat);
    case QDate::StandaloneFormat:
        return QLocale::system().standaloneDayName(weekday, QLocale::LongFormat);
    }
    return QString();
}
#endif // textdate && deprecated

#if QT_CONFIG(datestring) // depends on, so implies, textdate

static QString toStringTextDate(QDate date, QCalendar cal)
{
    if (date.isValid()) {
        const auto parts = cal.partsFromDate(date);
        if (parts.isValid()) {
            const QLatin1Char sp(' ');
            return QLocale::system().dayName(cal.dayOfWeek(date), QLocale::ShortFormat) + sp
                + cal.monthName(QLocale::system(), parts.month, parts.year, QLocale::ShortFormat)
                + sp + QString::number(parts.day) + sp + QString::number(parts.year);
        }
    }
    return QString();
}

static QString toStringTextDate(QDate date)
{
    return toStringTextDate(date, QCalendar());
}

static QString toStringIsoDate(const QDate &date)
{
    const auto parts = QCalendar().partsFromDate(date);
    if (parts.isValid() && parts.year >= 0 && parts.year <= 9999)
        return QString::asprintf("%04d-%02d-%02d", parts.year, parts.month, parts.day);
    return QString();
}

/*!
    \fn QString QDate::toString(Qt::DateFormat format) const

    \overload

    Returns the date as a string. The \a format parameter determines
    the format of the string.

    If the \a format is Qt::TextDate, the string is formatted in the default
    way. The day and month names will be localized names using the system
    locale, i.e. QLocale::system(). An example of this formatting
    is "Sat May 20 1995".

    If the \a format is Qt::ISODate, the string format corresponds
    to the ISO 8601 extended specification for representations of
    dates and times, taking the form yyyy-MM-dd, where yyyy is the
    year, MM is the month of the year (between 01 and 12), and dd is
    the day of the month between 01 and 31.

    If the \a format is Qt::SystemLocaleShortDate or
    Qt::SystemLocaleLongDate, the string format depends on the locale
    settings of the system. Identical to calling
    QLocale::system().toString(date, QLocale::ShortFormat) or
    QLocale::system().toString(date, QLocale::LongFormat).

    If the \a format is Qt::DefaultLocaleShortDate or
    Qt::DefaultLocaleLongDate, the string format depends on the
    default application locale. This is the locale set with
    QLocale::setDefault(), or the system locale if no default locale
    has been set. Identical to calling
    \l {QLocale::toString()}{QLocale().toString(date, QLocale::ShortFormat) } or
    \l {QLocale::toString()}{QLocale().toString(date, QLocale::LongFormat)}.

    If the \a format is Qt::RFC2822Date, the string is formatted in
    an \l{RFC 2822} compatible way. An example of this formatting is
    "20 May 1995".

    If the date is invalid, an empty string will be returned.

    \warning The Qt::ISODate format is only valid for years in the
    range 0 to 9999. This restriction may apply to locale-aware
    formats as well, depending on the locale settings.

    \sa fromString(), QLocale::toString()
*/
QString QDate::toString(Qt::DateFormat format) const
{
    if (!isValid())
        return QString();

    switch (format) {
    case Qt::SystemLocaleDate:
    case Qt::SystemLocaleShortDate:
        return QLocale::system().toString(*this, QLocale::ShortFormat);
    case Qt::SystemLocaleLongDate:
        return QLocale::system().toString(*this, QLocale::LongFormat);
    case Qt::LocaleDate:
    case Qt::DefaultLocaleShortDate:
        return QLocale().toString(*this, QLocale::ShortFormat);
    case Qt::DefaultLocaleLongDate:
        return QLocale().toString(*this, QLocale::LongFormat);
    case Qt::RFC2822Date:
        return QLocale::c().toString(*this, u"dd MMM yyyy");
    default:
    case Qt::TextDate:
        return toStringTextDate(*this);
    case Qt::ISODate:
    case Qt::ISODateWithMs:
        return toStringIsoDate(*this);
    }
}

/*!
    \fn QString QDate::toString(const QString &format) const
    \fn QString QDate::toString(QStringView format) const

    Returns the date as a string. The \a format parameter determines
    the format of the result string.

    These expressions may be used:

    \table
    \header \li Expression \li Output
    \row \li d \li The day as a number without a leading zero (1 to 31)
    \row \li dd \li The day as a number with a leading zero (01 to 31)
    \row \li ddd
         \li The abbreviated localized day name (e.g. 'Mon' to 'Sun').
             Uses the system locale to localize the name, i.e. QLocale::system().
    \row \li dddd
         \li The long localized day name (e.g. 'Monday' to 'Sunday').
             Uses the system locale to localize the name, i.e. QLocale::system().
    \row \li M \li The month as a number without a leading zero (1 to 12)
    \row \li MM \li The month as a number with a leading zero (01 to 12)
    \row \li MMM
         \li The abbreviated localized month name (e.g. 'Jan' to 'Dec').
             Uses the system locale to localize the name, i.e. QLocale::system().
    \row \li MMMM
         \li The long localized month name (e.g. 'January' to 'December').
             Uses the system locale to localize the name, i.e. QLocale::system().
    \row \li yy \li The year as a two digit number (00 to 99)
    \row \li yyyy \li The year as a four digit number. If the year is negative,
            a minus sign is prepended, making five characters.
    \endtable

    Any sequence of characters enclosed in single quotes will be included
    verbatim in the output string (stripped of the quotes), even if it contains
    formatting characters. Two consecutive single quotes ("''") are replaced by
    a single quote in the output. All other characters in the format string are
    included verbatim in the output string.

    Formats without separators (e.g. "ddMM") are supported but must be used with
    care, as the resulting strings aren't always reliably readable (e.g. if "dM"
    produces "212" it could mean either the 2nd of December or the 21st of
    February).

    Example format strings (assuming that the QDate is the 20 July
    1969):

    \table
    \header \li Format            \li Result
    \row    \li dd.MM.yyyy        \li 20.07.1969
    \row    \li ddd MMMM d yy     \li Sun July 20 69
    \row    \li 'The day is' dddd \li The day is Sunday
    \endtable

    If the datetime is invalid, an empty string will be returned.

    \sa fromString(), QDateTime::toString(), QTime::toString(), QLocale::toString()

*/
QString QDate::toString(QStringView format) const
{
    return QLocale::system().toString(*this, format); // QLocale::c() ### Qt6
}

#if QT_STRINGVIEW_LEVEL < 2
QString QDate::toString(const QString &format) const
{
    return toString(qToStringViewIgnoringNull(format));
}
#endif

QString QDate::toString(Qt::DateFormat format, QCalendar cal) const
{
    if (!isValid())
        return QString();

    switch (format) {
    case Qt::SystemLocaleDate:
    case Qt::SystemLocaleShortDate:
        return QLocale::system().toString(*this, QLocale::ShortFormat, cal);
    case Qt::SystemLocaleLongDate:
        return QLocale::system().toString(*this, QLocale::LongFormat, cal);
    case Qt::LocaleDate:
    case Qt::DefaultLocaleShortDate:
        return QLocale().toString(*this, QLocale::ShortFormat, cal);
    case Qt::DefaultLocaleLongDate:
        return QLocale().toString(*this, QLocale::LongFormat, cal);
    case Qt::RFC2822Date:
        return QLocale::c().toString(*this, QStringView(u"dd MMM yyyy"), cal);
    default:
    case Qt::TextDate:
        return toStringTextDate(*this, cal);
    case Qt::ISODate:
    case Qt::ISODateWithMs:
        return toStringIsoDate(*this);
    }
}

QString QDate::toString(QStringView format, QCalendar cal) const
{
    return QLocale::system().toString(*this, format, cal); // QLocale::c() ### Qt6
}

#if QT_STRINGVIEW_LEVEL < 2
QString QDate::toString(const QString &format, QCalendar cal) const
{
    return toString(qToStringViewIgnoringNull(format), cal);
}
#endif

#endif // datestring

/*!
    \fn bool QDate::setYMD(int y, int m, int d)

    \deprecated in 5.0, use setDate() instead.

    Sets the date's year \a y, month \a m, and day \a d.

    If \a y is in the range 0 to 99, it is interpreted as 1900 to
    1999.
    Returns \c false if the date is invalid.

    Use setDate() instead.
*/

/*!
    \since 4.2

    Sets this to represent the date, in the Gregorian calendar, with the given
    \a year, \a month and \a day numbers. Returns true if the resulting date is
    valid, otherwise it sets this to represent an invalid date and returns
    false.

    \sa isValid(), QCalendar::dateFromParts()
*/
bool QDate::setDate(int year, int month, int day)
{
    if (QGregorianCalendar::julianFromParts(year, month, day, &jd))
        return true;

    jd = nullJd();
    return false;
}

/*!
    \since 5.14

    Sets this to represent the date, in the given calendar \a cal, with the
    given \a year, \a month and \a day numbers. Returns true if the resulting
    date is valid, otherwise it sets this to represent an invalid date and
    returns false.

    \sa isValid(), QCalendar::dateFromParts()
*/

bool QDate::setDate(int year, int month, int day, QCalendar cal)
{
    *this = QDate(year, month, day, cal);
    return isValid();
}

/*!
    \since 4.5

    Extracts the date's year, month, and day, and assigns them to
    *\a year, *\a month, and *\a day. The pointers may be null.

    Returns 0 if the date is invalid.

    \note In Qt versions prior to 5.7, this function is marked as non-\c{const}.

    \sa year(), month(), day(), isValid(), QCalendar::partsFromDate()
*/
void QDate::getDate(int *year, int *month, int *day) const
{
    QCalendar::YearMonthDay parts; // invalid by default
    if (isValid())
        parts = QGregorianCalendar::partsFromJulian(jd);

    const bool ok = parts.isValid();
    if (year)
        *year = ok ? parts.year : 0;
    if (month)
        *month = ok ? parts.month : 0;
    if (day)
        *day = ok ? parts.day : 0;
}

#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
/*!
    \overload
    \internal
*/
void QDate::getDate(int *year, int *month, int *day)
{
    qAsConst(*this).getDate(year, month, day);
}
#endif // < Qt 6

/*!
    Returns a QDate object containing a date \a ndays later than the
    date of this object (or earlier if \a ndays is negative).

    Returns a null date if the current date is invalid or the new date is
    out of range.

    \sa addMonths(), addYears(), daysTo()
*/

QDate QDate::addDays(qint64 ndays) const
{
    if (isNull())
        return QDate();

    // Due to limits on minJd() and maxJd() we know that any overflow
    // will be invalid and caught by fromJulianDay().
    return fromJulianDay(jd + ndays);
}

/*!
    Returns a QDate object containing a date \a nmonths later than the
    date of this object (or earlier if \a nmonths is negative).

    Uses \a cal as calendar, if supplied, else the Gregorian calendar.

    \note If the ending day/month combination does not exist in the resulting
    month/year, this function will return a date that is the latest valid date
    in the selected month.

    \sa addDays(), addYears()
*/

QDate QDate::addMonths(int nmonths, QCalendar cal) const
{
    if (!isValid())
        return QDate();

    if (nmonths == 0)
        return *this;

    auto parts = cal.partsFromDate(*this);

    if (!parts.isValid())
        return QDate();
    Q_ASSERT(parts.year || cal.hasYearZero());

    parts.month += nmonths;
    while (parts.month <= 0) {
        if (--parts.year || cal.hasYearZero())
            parts.month += cal.monthsInYear(parts.year);
    }
    int count = cal.monthsInYear(parts.year);
    while (parts.month > count) {
        parts.month -= count;
        count = (++parts.year || cal.hasYearZero()) ? cal.monthsInYear(parts.year) : 0;
    }

    return fixedDate(std::move(parts), cal);
}

/*!
  \overload
*/

QDate QDate::addMonths(int nmonths) const
{
    if (isNull())
        return QDate();

    if (nmonths == 0)
        return *this;

    auto parts = QGregorianCalendar::partsFromJulian(jd);

    if (!parts.isValid())
        return QDate();
    Q_ASSERT(parts.year);

    parts.month += nmonths;
    while (parts.month <= 0) {
        if (--parts.year) // skip over year 0
            parts.month += 12;
    }
    while (parts.month > 12) {
        parts.month -= 12;
        if (!++parts.year) // skip over year 0
            ++parts.year;
    }

    return fixedDate(std::move(parts));
}

/*!
    Returns a QDate object containing a date \a nyears later than the
    date of this object (or earlier if \a nyears is negative).

    Uses \a cal as calendar, if supplied, else the Gregorian calendar.

    \note If the ending day/month combination does not exist in the resulting
    year (e.g., for the Gregorian calendar, if the date was Feb 29 and the final
    year is not a leap year), this function will return a date that is the
    latest valid date in the given month (in the example, Feb 28).

    \sa addDays(), addMonths()
*/

QDate QDate::addYears(int nyears, QCalendar cal) const
{
    if (!isValid())
        return QDate();

    auto parts = cal.partsFromDate(*this);
    if (!parts.isValid())
        return QDate();

    int old_y = parts.year;
    parts.year += nyears;

    // If we just crossed (or hit) a missing year zero, adjust year by +/- 1:
    if (!cal.hasYearZero() && ((old_y > 0) != (parts.year > 0) || !parts.year))
        parts.year += nyears > 0 ? +1 : -1;

    return fixedDate(std::move(parts), cal);
}

/*!
    \overload
*/

QDate QDate::addYears(int nyears) const
{
    if (isNull())
        return QDate();

    auto parts = QGregorianCalendar::partsFromJulian(jd);
    if (!parts.isValid())
        return QDate();

    int old_y = parts.year;
    parts.year += nyears;

    // If we just crossed (or hit) a missing year zero, adjust year by +/- 1:
    if ((old_y > 0) != (parts.year > 0) || !parts.year)
        parts.year += nyears > 0 ? +1 : -1;

    return fixedDate(std::move(parts));
}

/*!
    Returns the number of days from this date to \a d (which is
    negative if \a d is earlier than this date).

    Returns 0 if either date is invalid.

    Example:
    \snippet code/src_corelib_tools_qdatetime.cpp 0

    \sa addDays()
*/

qint64 QDate::daysTo(const QDate &d) const
{
    if (isNull() || d.isNull())
        return 0;

    // Due to limits on minJd() and maxJd() we know this will never overflow
    return d.jd - jd;
}


/*!
    \fn bool QDate::operator==(const QDate &d) const

    Returns \c true if this date is equal to \a d; otherwise returns
    false.

*/

/*!
    \fn bool QDate::operator!=(const QDate &d) const

    Returns \c true if this date is different from \a d; otherwise
    returns \c false.
*/

/*!
    \fn bool QDate::operator<(const QDate &d) const

    Returns \c true if this date is earlier than \a d; otherwise returns
    false.
*/

/*!
    \fn bool QDate::operator<=(const QDate &d) const

    Returns \c true if this date is earlier than or equal to \a d;
    otherwise returns \c false.
*/

/*!
    \fn bool QDate::operator>(const QDate &d) const

    Returns \c true if this date is later than \a d; otherwise returns
    false.
*/

/*!
    \fn bool QDate::operator>=(const QDate &d) const

    Returns \c true if this date is later than or equal to \a d;
    otherwise returns \c false.
*/

/*!
    \fn QDate::currentDate()
    Returns the current date, as reported by the system clock.

    \sa QTime::currentTime(), QDateTime::currentDateTime()
*/

#if QT_CONFIG(datestring) // depends on, so implies, textdate
namespace {

struct ParsedInt { int value = 0; bool ok = false; };

/*
    /internal

    Read an int that must be the whole text.  QStringRef::toInt() will ignore
    spaces happily; but ISO date format should not.
*/
ParsedInt readInt(QStringView text)
{
    ParsedInt result;
    for (const auto &ch : text) {
        if (ch.isSpace())
            return result;
    }
    result.value = QLocale::c().toInt(text, &result.ok);
    return result;
}

}

/*!
    Returns the QDate represented by the \a string, using the
    \a format given, or an invalid date if the string cannot be
    parsed.

    Note for Qt::TextDate: It is recommended that you use the
    English short month names (e.g. "Jan"). Although localized month
    names can also be used, they depend on the user's locale settings.

    \sa toString(), QLocale::toDate()
*/

QDate QDate::fromString(const QString &string, Qt::DateFormat format)
{
    if (string.isEmpty())
        return QDate();

    switch (format) {
    case Qt::SystemLocaleDate:
    case Qt::SystemLocaleShortDate:
        return QLocale::system().toDate(string, QLocale::ShortFormat);
    case Qt::SystemLocaleLongDate:
        return QLocale::system().toDate(string, QLocale::LongFormat);
    case Qt::LocaleDate:
    case Qt::DefaultLocaleShortDate:
        return QLocale().toDate(string, QLocale::ShortFormat);
    case Qt::DefaultLocaleLongDate:
        return QLocale().toDate(string, QLocale::LongFormat);
    case Qt::RFC2822Date:
        return rfcDateImpl(string).date;
    default:
    case Qt::TextDate: {
        QVector<QStringRef> parts = string.splitRef(QLatin1Char(' '), QString::SkipEmptyParts);

        if (parts.count() != 4)
            return QDate();

        bool ok = false;
        int year = parts.at(3).toInt(&ok);
        int day = ok ? parts.at(2).toInt(&ok) : 0;
        if (!ok || !day)
            return QDate();

        const int month = fromShortMonthName(parts.at(1), year);
        if (month == -1) // Month name matches no English or localised name.
            return QDate();

        return QDate(year, month, day);
        }
    case Qt::ISODate:
        // Semi-strict parsing, must be long enough and have punctuators as separators
        if (string.size() >= 10 && string.at(4).isPunct() && string.at(7).isPunct()
                && (string.size() == 10 || !string.at(10).isDigit())) {
            QStringView view(string);
            const ParsedInt year = readInt(view.mid(0, 4));
            const ParsedInt month = readInt(view.mid(5, 2));
            const ParsedInt day = readInt(view.mid(8, 2));
            if (year.ok && year.value > 0 && year.value <= 9999 && month.ok && day.ok)
                return QDate(year.value, month.value, day.value);
        }
        break;
    }
    return QDate();
}

/*!
    Returns the QDate represented by the \a string, using the \a
    format given, or an invalid date if the string cannot be parsed.

    Uses \a cal as calendar if supplied, else the Gregorian calendar. Ranges of
    values in the format descriptions below are for the latter; they may be
    different for other calendars.

    These expressions may be used for the format:

    \table
    \header \li Expression \li Output
    \row \li d \li The day as a number without a leading zero (1 to 31)
    \row \li dd \li The day as a number with a leading zero (01 to 31)
    \row \li ddd
         \li The abbreviated localized day name (e.g. 'Mon' to 'Sun').
             Uses the system locale to localize the name, i.e. QLocale::system().
    \row \li dddd
         \li The long localized day name (e.g. 'Monday' to 'Sunday').
             Uses the system locale to localize the name, i.e. QLocale::system().
    \row \li M \li The month as a number without a leading zero (1 to 12)
    \row \li MM \li The month as a number with a leading zero (01 to 12)
    \row \li MMM
         \li The abbreviated localized month name (e.g. 'Jan' to 'Dec').
             Uses the system locale to localize the name, i.e. QLocale::system().
    \row \li MMMM
         \li The long localized month name (e.g. 'January' to 'December').
             Uses the system locale to localize the name, i.e. QLocale::system().
    \row \li yy \li The year as a two digit number (00 to 99)
    \row \li yyyy \li The year as a four digit number, possibly plus a leading
             minus sign for negative years.
    \endtable

    \note Unlike the other version of this function, day and month names must
    be given in the user's local language. It is only possible to use the English
    names if the user's language is English.

    All other input characters will be treated as text. Any sequence
    of characters that are enclosed in single quotes will also be
    treated as text and will not be used as an expression. For example:

    \snippet code/src_corelib_tools_qdatetime.cpp 1

    If the format is not satisfied, an invalid QDate is returned. The
    expressions that don't expect leading zeroes (d, M) will be
    greedy. This means that they will use two digits even if this
    will put them outside the accepted range of values and leaves too
    few digits for other sections. For example, the following format
    string could have meant January 30 but the M will grab two
    digits, resulting in an invalid date:

    \snippet code/src_corelib_tools_qdatetime.cpp 2

    For any field that is not represented in the format the following
    defaults are used:

    \table
    \header \li Field  \li Default value
    \row    \li Year   \li 1900
    \row    \li Month  \li 1
    \row    \li Day    \li 1
    \endtable

    The following examples demonstrate the default values:

    \snippet code/src_corelib_tools_qdatetime.cpp 3

    \sa toString(), QDateTime::fromString(), QTime::fromString(),
        QLocale::toDate()
*/

QDate QDate::fromString(const QString &string, const QString &format, QCalendar cal)
{
    QDate date;
#if QT_CONFIG(datetimeparser)
    QDateTimeParser dt(QVariant::Date, QDateTimeParser::FromString, cal);
    // dt.setDefaultLocale(QLocale::c()); ### Qt 6
    if (dt.parseFormat(format))
        dt.fromString(string, &date, 0);
#else
    Q_UNUSED(string);
    Q_UNUSED(format);
    Q_UNUSED(cal);
#endif
    return date;
}

/*!
  \overload
*/

QDate QDate::fromString(const QString &string, const QString &format)
{
    return fromString(string, format, QCalendar());
}
#endif // datestring

/*!
    \overload

    Returns \c true if the specified date (\a year, \a month, and \a day) is
    valid in the Gregorian calendar; otherwise returns \c false.

    Example:
    \snippet code/src_corelib_tools_qdatetime.cpp 4

    \sa isNull(), setDate(), QCalendar::isDateValid()
*/

bool QDate::isValid(int year, int month, int day)
{
    return QGregorianCalendar::validParts(year, month, day);
}

/*!
    \fn bool QDate::isLeapYear(int year)

    Returns \c true if the specified \a year is a leap year in the Gregorian
    calendar; otherwise returns \c false.

    \sa QCalendar::isLeapYear()
*/

bool QDate::isLeapYear(int y)
{
    return QGregorianCalendar::leapTest(y);
}

/*! \fn static QDate QDate::fromJulianDay(qint64 jd)

    Converts the Julian day \a jd to a QDate.

    \sa toJulianDay()
*/

/*! \fn int QDate::toJulianDay() const

    Converts the date to a Julian day.

    \sa fromJulianDay()
*/

/*****************************************************************************
  QTime member functions
 *****************************************************************************/

/*!
    \class QTime
    \inmodule QtCore
    \reentrant

    \brief The QTime class provides clock time functions.


    A QTime object contains a clock time, which it can express as the numbers of
    hours, minutes, seconds, and milliseconds since midnight. It provides
    functions for comparing times and for manipulating a time by adding a number
    of milliseconds.

    QTime uses the 24-hour clock format; it has no concept of AM/PM.
    Unlike QDateTime, QTime knows nothing about time zones or
    daylight-saving time (DST).

    A QTime object is typically created either by giving the number of hours,
    minutes, seconds, and milliseconds explicitly, or by using the static
    function currentTime(), which creates a QTime object that represents the
    system's local time.

    The hour(), minute(), second(), and msec() functions provide
    access to the number of hours, minutes, seconds, and milliseconds
    of the time. The same information is provided in textual format by
    the toString() function.

    The addSecs() and addMSecs() functions provide the time a given
    number of seconds or milliseconds later than a given time.
    Correspondingly, the number of seconds or milliseconds
    between two times can be found using secsTo() or msecsTo().

    QTime provides a full set of operators to compare two QTime
    objects; an earlier time is considered smaller than a later one;
    if A.msecsTo(B) is positive, then A < B.

    \sa QDate, QDateTime
*/

/*!
    \fn QTime::QTime()

    Constructs a null time object. For a null time, isNull() returns \c true and
    isValid() returns \c false. If you need a zero time, use QTime(0, 0).  For
    the start of a day, see QDate::startOfDay().

    \sa isNull(), isValid()
*/

/*!
    Constructs a time with hour \a h, minute \a m, seconds \a s and
    milliseconds \a ms.

    \a h must be in the range 0 to 23, \a m and \a s must be in the
    range 0 to 59, and \a ms must be in the range 0 to 999.

    \sa isValid()
*/

QTime::QTime(int h, int m, int s, int ms)
{
    setHMS(h, m, s, ms);
}


/*!
    \fn bool QTime::isNull() const

    Returns \c true if the time is null (i.e., the QTime object was
    constructed using the default constructor); otherwise returns
    false. A null time is also an invalid time.

    \sa isValid()
*/

/*!
    Returns \c true if the time is valid; otherwise returns \c false. For example,
    the time 23:30:55.746 is valid, but 24:12:30 is invalid.

    \sa isNull()
*/

bool QTime::isValid() const
{
    return mds > NullTime && mds < MSECS_PER_DAY;
}


/*!
    Returns the hour part (0 to 23) of the time.

    Returns -1 if the time is invalid.

    \sa minute(), second(), msec()
*/

int QTime::hour() const
{
    if (!isValid())
        return -1;

    return ds() / MSECS_PER_HOUR;
}

/*!
    Returns the minute part (0 to 59) of the time.

    Returns -1 if the time is invalid.

    \sa hour(), second(), msec()
*/

int QTime::minute() const
{
    if (!isValid())
        return -1;

    return (ds() % MSECS_PER_HOUR) / MSECS_PER_MIN;
}

/*!
    Returns the second part (0 to 59) of the time.

    Returns -1 if the time is invalid.

    \sa hour(), minute(), msec()
*/

int QTime::second() const
{
    if (!isValid())
        return -1;

    return (ds() / 1000)%SECS_PER_MIN;
}

/*!
    Returns the millisecond part (0 to 999) of the time.

    Returns -1 if the time is invalid.

    \sa hour(), minute(), second()
*/

int QTime::msec() const
{
    if (!isValid())
        return -1;

    return ds() % 1000;
}

#if QT_CONFIG(datestring) // depends on, so implies, textdate
/*!
    \overload

    Returns the time as a string. The \a format parameter determines
    the format of the string.

    If \a format is Qt::TextDate, the string format is HH:mm:ss;
    e.g. 1 second before midnight would be "23:59:59".

    If \a format is Qt::ISODate, the string format corresponds to the
    ISO 8601 extended specification for representations of dates,
    represented by HH:mm:ss. To include milliseconds in the ISO 8601
    date, use the \a format Qt::ISODateWithMs, which corresponds to
    HH:mm:ss.zzz.

    If the \a format is Qt::SystemLocaleShortDate or
    Qt::SystemLocaleLongDate, the string format depends on the locale
    settings of the system. Identical to calling
    QLocale::system().toString(time, QLocale::ShortFormat) or
    QLocale::system().toString(time, QLocale::LongFormat).

    If the \a format is Qt::DefaultLocaleShortDate or
    Qt::DefaultLocaleLongDate, the string format depends on the
    default application locale. This is the locale set with
    QLocale::setDefault(), or the system locale if no default locale
    has been set. Identical to calling

    \l {QLocale::toString()}{QLocale().toString(time, QLocale::ShortFormat)} or
    \l {QLocale::toString()}{QLocale().toString(time, QLocale::LongFormat)}.

    If the \a format is Qt::RFC2822Date, the string is formatted in
    an \l{RFC 2822} compatible way. An example of this formatting is
    "23:59:20".

    If the time is invalid, an empty string will be returned.

    \sa fromString(), QDate::toString(), QDateTime::toString(), QLocale::toString()
*/

QString QTime::toString(Qt::DateFormat format) const
{
    if (!isValid())
        return QString();

    switch (format) {
    case Qt::SystemLocaleDate:
    case Qt::SystemLocaleShortDate:
        return QLocale::system().toString(*this, QLocale::ShortFormat);
    case Qt::SystemLocaleLongDate:
        return QLocale::system().toString(*this, QLocale::LongFormat);
    case Qt::LocaleDate:
    case Qt::DefaultLocaleShortDate:
        return QLocale().toString(*this, QLocale::ShortFormat);
    case Qt::DefaultLocaleLongDate:
        return QLocale().toString(*this, QLocale::LongFormat);
    case Qt::ISODateWithMs:
        return QString::asprintf("%02d:%02d:%02d.%03d", hour(), minute(), second(), msec());
    case Qt::RFC2822Date:
    case Qt::ISODate:
    case Qt::TextDate:
    default:
        return QString::asprintf("%02d:%02d:%02d", hour(), minute(), second());
    }
}

/*!
    \fn QString QTime::toString(const QString &format) const
    \fn QString QTime::toString(QStringView format) const

    Returns the time as a string. The \a format parameter determines
    the format of the result string.

    These expressions may be used:

    \table
    \header \li Expression \li Output
    \row \li h
         \li The hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
    \row \li hh
         \li The hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
    \row \li H
         \li The hour without a leading zero (0 to 23, even with AM/PM display)
    \row \li HH
         \li The hour with a leading zero (00 to 23, even with AM/PM display)
    \row \li m \li The minute without a leading zero (0 to 59)
    \row \li mm \li The minute with a leading zero (00 to 59)
    \row \li s \li The whole second, without any leading zero (0 to 59)
    \row \li ss \li The whole second, with a leading zero where applicable (00 to 59)
    \row \li z \li The fractional part of the second, to go after a decimal
                point, without trailing zeroes (0 to 999).  Thus "\c{s.z}"
                reports the seconds to full available (millisecond) precision
                without trailing zeroes.
    \row \li zzz \li The fractional part of the second, to millisecond
                precision, including trailing zeroes where applicable (000 to 999).
    \row \li AP or A
         \li Use AM/PM display. \e A/AP will be replaced by an upper-case
             version of either QLocale::amText() or QLocale::pmText().
    \row \li ap or a
         \li Use am/pm display. \e a/ap will be replaced by a lower-case version
             of either QLocale::amText() or QLocale::pmText().
    \row \li t \li The timezone (for example "CEST")
    \endtable

    Any sequence of characters enclosed in single quotes will be included
    verbatim in the output string (stripped of the quotes), even if it contains
    formatting characters. Two consecutive single quotes ("''") are replaced by
    a single quote in the output. All other characters in the format string are
    included verbatim in the output string.

    Formats without separators (e.g. "ddMM") are supported but must be used with
    care, as the resulting strings aren't always reliably readable (e.g. if "dM"
    produces "212" it could mean either the 2nd of December or the 21st of
    February).

    Example format strings (assuming that the QTime is 14:13:09.042 and the system
    locale is \c{en_US})

    \table
    \header \li Format \li Result
    \row \li hh:mm:ss.zzz \li 14:13:09.042
    \row \li h:m:s ap     \li 2:13:9 pm
    \row \li H:m:s a      \li 14:13:9 pm
    \endtable

    If the time is invalid, an empty string will be returned.
    If \a format is empty, the default format "hh:mm:ss" is used.

    \sa fromString(), QDate::toString(), QDateTime::toString(), QLocale::toString()
*/
QString QTime::toString(QStringView format) const
{
    return QLocale::system().toString(*this, format); // QLocale::c() ### Qt6
}

#if QT_STRINGVIEW_VERSION < 2
QString QTime::toString(const QString &format) const
{
    return toString(qToStringViewIgnoringNull(format));
}
#endif

#endif // datestring

/*!
    Sets the time to hour \a h, minute \a m, seconds \a s and
    milliseconds \a ms.

    \a h must be in the range 0 to 23, \a m and \a s must be in the
    range 0 to 59, and \a ms must be in the range 0 to 999.
    Returns \c true if the set time is valid; otherwise returns \c false.

    \sa isValid()
*/

bool QTime::setHMS(int h, int m, int s, int ms)
{
    if (!isValid(h,m,s,ms)) {
        mds = NullTime;                // make this invalid
        return false;
    }
    mds = (h*SECS_PER_HOUR + m*SECS_PER_MIN + s)*1000 + ms;
    return true;
}

/*!
    Returns a QTime object containing a time \a s seconds later
    than the time of this object (or earlier if \a s is negative).

    Note that the time will wrap if it passes midnight.

    Returns a null time if this time is invalid.

    Example:

    \snippet code/src_corelib_tools_qdatetime.cpp 5

    \sa addMSecs(), secsTo(), QDateTime::addSecs()
*/

QTime QTime::addSecs(int s) const
{
    s %= SECS_PER_DAY;
    return addMSecs(s * 1000);
}

/*!
    Returns the number of seconds from this time to \a t.
    If \a t is earlier than this time, the number of seconds returned
    is negative.

    Because QTime measures time within a day and there are 86400
    seconds in a day, the result is always between -86400 and 86400.

    secsTo() does not take into account any milliseconds.

    Returns 0 if either time is invalid.

    \sa addSecs(), QDateTime::secsTo()
*/

int QTime::secsTo(const QTime &t) const
{
    if (!isValid() || !t.isValid())
        return 0;

    // Truncate milliseconds as we do not want to consider them.
    int ourSeconds = ds() / 1000;
    int theirSeconds = t.ds() / 1000;
    return theirSeconds - ourSeconds;
}

/*!
    Returns a QTime object containing a time \a ms milliseconds later
    than the time of this object (or earlier if \a ms is negative).

    Note that the time will wrap if it passes midnight. See addSecs()
    for an example.

    Returns a null time if this time is invalid.

    \sa addSecs(), msecsTo(), QDateTime::addMSecs()
*/

QTime QTime::addMSecs(int ms) const
{
    QTime t;
    if (isValid()) {
        if (ms < 0) {
            // %,/ not well-defined for -ve, so always work with +ve.
            int negdays = (MSECS_PER_DAY - ms) / MSECS_PER_DAY;
            t.mds = (ds() + ms + negdays * MSECS_PER_DAY) % MSECS_PER_DAY;
        } else {
            t.mds = (ds() + ms) % MSECS_PER_DAY;
        }
    }
    return t;
}

/*!
    Returns the number of milliseconds from this time to \a t.
    If \a t is earlier than this time, the number of milliseconds returned
    is negative.

    Because QTime measures time within a day and there are 86400
    seconds in a day, the result is always between -86400000 and
    86400000 ms.

    Returns 0 if either time is invalid.

    \sa secsTo(), addMSecs(), QDateTime::msecsTo()
*/

int QTime::msecsTo(const QTime &t) const
{
    if (!isValid() || !t.isValid())
        return 0;
    return t.ds() - ds();
}


/*!
    \fn bool QTime::operator==(const QTime &t) const

    Returns \c true if this time is equal to \a t; otherwise returns \c false.
*/

/*!
    \fn bool QTime::operator!=(const QTime &t) const

    Returns \c true if this time is different from \a t; otherwise returns \c false.
*/

/*!
    \fn bool QTime::operator<(const QTime &t) const

    Returns \c true if this time is earlier than \a t; otherwise returns \c false.
*/

/*!
    \fn bool QTime::operator<=(const QTime &t) const

    Returns \c true if this time is earlier than or equal to \a t;
    otherwise returns \c false.
*/

/*!
    \fn bool QTime::operator>(const QTime &t) const

    Returns \c true if this time is later than \a t; otherwise returns \c false.
*/

/*!
    \fn bool QTime::operator>=(const QTime &t) const

    Returns \c true if this time is later than or equal to \a t;
    otherwise returns \c false.
*/

/*!
    \fn QTime QTime::fromMSecsSinceStartOfDay(int msecs)

    Returns a new QTime instance with the time set to the number of \a msecs
    since the start of the day, i.e. since 00:00:00.

    If \a msecs falls outside the valid range an invalid QTime will be returned.

    \sa msecsSinceStartOfDay()
*/

/*!
    \fn int QTime::msecsSinceStartOfDay() const

    Returns the number of msecs since the start of the day, i.e. since 00:00:00.

    \sa fromMSecsSinceStartOfDay()
*/

/*!
    \fn QTime::currentTime()

    Returns the current time as reported by the system clock.

    Note that the accuracy depends on the accuracy of the underlying
    operating system; not all systems provide 1-millisecond accuracy.

    Furthermore, currentTime() only increases within each day; it shall drop by
    24 hours each time midnight passes; and, beside this, changes in it may not
    correspond to elapsed time, if a daylight-saving transition intervenes.

    \sa QDateTime::currentDateTime(), QDateTime::currentDateTimeUtc()
*/

#if QT_CONFIG(datestring) // depends on, so implies, textdate

static QTime fromIsoTimeString(QStringView string, Qt::DateFormat format, bool *isMidnight24)
{
    if (isMidnight24)
        *isMidnight24 = false;

    const int size = string.size();
    if (size < 5 || string.at(2) != QLatin1Char(':'))
        return QTime();

    ParsedInt hour = readInt(string.mid(0, 2));
    ParsedInt minute = readInt(string.mid(3, 2));
    if (!hour.ok || !minute.ok)
        return QTime();
    // FIXME: ISO 8601 allows [,.]\d+ after hour, just as it does after minute

    int second = 0;
    int msec = 0;

    if (size == 5) {
        // HH:mm format
        second = 0;
        msec = 0;
    } else if (string.at(5) == QLatin1Char(',') || string.at(5) == QLatin1Char('.')) {
        if (format == Qt::TextDate)
            return QTime();
        // ISODate HH:mm.ssssss format
        // We only want 5 digits worth of fraction of minute. This follows the existing
        // behavior that determines how milliseconds are read; 4 millisecond digits are
        // read and then rounded to 3. If we read at most 5 digits for fraction of minute,
        // the maximum amount of millisecond digits it will expand to once converted to
        // seconds is 4. E.g. 12:34,99999 will expand to 12:34:59.9994. The milliseconds
        // will then be rounded up AND clamped to 999.

        const QStringView minuteFractionStr = string.mid(6, qMin(qsizetype(5), string.size() - 6));
        const ParsedInt parsed = readInt(minuteFractionStr);
        if (!parsed.ok)
            return QTime();
        const float secondWithMs
            = double(parsed.value) * 60 / (std::pow(double(10), minuteFractionStr.size()));

        second = std::floor(secondWithMs);
        const float secondFraction = secondWithMs - second;
        msec = qMin(qRound(secondFraction * 1000.0), 999);
    } else if (string.at(5) == QLatin1Char(':')) {
        // HH:mm:ss or HH:mm:ss.zzz
        const ParsedInt parsed = readInt(string.mid(6, qMin(qsizetype(2), string.size() - 6)));
        if (!parsed.ok)
            return QTime();
        second = parsed.value;
        if (size <= 8) {
            // No fractional part to read
        } else if (string.at(8) == QLatin1Char(',') || string.at(8) == QLatin1Char('.')) {
            QStringView msecStr(string.mid(9, qMin(qsizetype(4), string.size() - 9)));
            bool ok = true;
            // Can't use readInt() here, as we *do* allow trailing space - but not leading:
            if (!msecStr.isEmpty() && !msecStr.at(0).isDigit())
                return QTime();
            msecStr = msecStr.trimmed();
            int msecInt = msecStr.isEmpty() ? 0 : QLocale::c().toInt(msecStr, &ok);
            if (!ok)
                return QTime();
            const double secondFraction(msecInt / (std::pow(double(10), msecStr.size())));
            msec = qMin(qRound(secondFraction * 1000.0), 999);
        } else {
#if QT_VERSION >= QT_VERSION_CHECK(6,0,0) // behavior change
            // Stray cruft after date-time: tolerate trailing space, but nothing else.
            for (const auto &ch : string.mid(8)) {
                if (!ch.isSpace())
                    return QTime();
            }
#endif
        }
    } else {
        return QTime();
    }

    const bool isISODate = format == Qt::ISODate || format == Qt::ISODateWithMs;
    if (isISODate && hour.value == 24 && minute.value == 0 && second == 0 && msec == 0) {
        if (isMidnight24)
            *isMidnight24 = true;
        hour.value = 0;
    }

    return QTime(hour.value, minute.value, second, msec);
}

/*!
    Returns the time represented in the \a string as a QTime using the
    \a format given, or an invalid time if this is not possible.

    Note that fromString() uses a "C" locale encoded string to convert
    milliseconds to a float value. If the default locale is not "C",
    this may result in two conversion attempts (if the conversion
    fails for the default locale). This should be considered an
    implementation detail.

    \sa toString(), QLocale::toTime()
*/
QTime QTime::fromString(const QString &string, Qt::DateFormat format)
{
    if (string.isEmpty())
        return QTime();

    switch (format) {
    case Qt::SystemLocaleDate:
    case Qt::SystemLocaleShortDate:
        return QLocale::system().toTime(string, QLocale::ShortFormat);
    case Qt::SystemLocaleLongDate:
        return QLocale::system().toTime(string, QLocale::LongFormat);
    case Qt::LocaleDate:
    case Qt::DefaultLocaleShortDate:
        return QLocale().toTime(string, QLocale::ShortFormat);
    case Qt::DefaultLocaleLongDate:
        return QLocale().toTime(string, QLocale::LongFormat);
    case Qt::RFC2822Date:
        return rfcDateImpl(string).time;
    case Qt::ISODate:
    case Qt::ISODateWithMs:
    case Qt::TextDate:
    default:
        return fromIsoTimeString(QStringView(string), format, nullptr);
    }
}

/*!
    Returns the QTime represented by the \a string, using the \a
    format given, or an invalid time if the string cannot be parsed.

    These expressions may be used for the format:

    \table
    \header \li Expression \li Output
    \row \li h
         \li The hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
    \row \li hh
         \li The hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
    \row \li H
         \li The hour without a leading zero (0 to 23, even with AM/PM display)
    \row \li HH
         \li The hour with a leading zero (00 to 23, even with AM/PM display)
    \row \li m \li The minute without a leading zero (0 to 59)
    \row \li mm \li The minute with a leading zero (00 to 59)
    \row \li s \li The whole second, without any leading zero (0 to 59)
    \row \li ss \li The whole second, with a leading zero where applicable (00 to 59)
    \row \li z \li The fractional part of the second, to go after a decimal
                point, without trailing zeroes (0 to 999).  Thus "\c{s.z}"
                reports the seconds to full available (millisecond) precision
                without trailing zeroes.
    \row \li zzz \li The fractional part of the second, to millisecond
                precision, including trailing zeroes where applicable (000 to 999).
    \row \li AP or A
         \li Interpret as an AM/PM time. \e A/AP will match an upper-case
             version of either QLocale::amText() or QLocale::pmText().
    \row \li ap or a
         \li Interpret as an am/pm time. \e a/ap will match a lower-case version
             of either QLocale::amText() or QLocale::pmText().
    \row \li t \li the timezone (for example "CEST")
    \endtable

    All other input characters will be treated as text. Any sequence
    of characters that are enclosed in single quotes will also be
    treated as text and not be used as an expression.

    \snippet code/src_corelib_tools_qdatetime.cpp 6

    If the format is not satisfied, an invalid QTime is returned.
    Expressions that do not expect leading zeroes to be given (h, m, s
    and z) are greedy. This means that they will use two digits even if
    this puts them outside the range of accepted values and leaves too
    few digits for other sections. For example, the following string
    could have meant 00:07:10, but the m will grab two digits, resulting
    in an invalid time:

    \snippet code/src_corelib_tools_qdatetime.cpp 7

    Any field that is not represented in the format will be set to zero.
    For example:

    \snippet code/src_corelib_tools_qdatetime.cpp 8

    \sa toString(), QDateTime::fromString(), QDate::fromString(),
    QLocale::toTime()
*/

QTime QTime::fromString(const QString &string, const QString &format)
{
    QTime time;
#if QT_CONFIG(datetimeparser)
    QDateTimeParser dt(QVariant::Time, QDateTimeParser::FromString, QCalendar());
    // dt.setDefaultLocale(QLocale::c()); ### Qt 6
    if (dt.parseFormat(format))
        dt.fromString(string, 0, &time);
#else
    Q_UNUSED(string);
    Q_UNUSED(format);
#endif
    return time;
}

#endif // datestring


/*!
    \overload

    Returns \c true if the specified time is valid; otherwise returns
    false.

    The time is valid if \a h is in the range 0 to 23, \a m and
    \a s are in the range 0 to 59, and \a ms is in the range 0 to 999.

    Example:

    \snippet code/src_corelib_tools_qdatetime.cpp 9
*/

bool QTime::isValid(int h, int m, int s, int ms)
{
    return (uint)h < 24 && (uint)m < 60 && (uint)s < 60 && (uint)ms < 1000;
}

#if QT_DEPRECATED_SINCE(5, 14) // ### Qt 6: remove
/*!
    Sets this time to the current time. This is practical for timing:

    \snippet code/src_corelib_tools_qdatetime.cpp 10

    \sa restart(), elapsed(), currentTime()
*/

void QTime::start()
{
    *this = currentTime();
}

/*!
    Sets this time to the current time and returns the number of
    milliseconds that have elapsed since the last time start() or
    restart() was called.

    This function is guaranteed to be atomic and is thus very handy
    for repeated measurements. Call start() to start the first
    measurement, and restart() for each later measurement.

    Note that the counter wraps to zero 24 hours after the last call
    to start() or restart().

    \warning If the system's clock setting has been changed since the
    last time start() or restart() was called, the result is
    undefined. This can happen when daylight-saving time is turned on
    or off.

    \sa start(), elapsed(), currentTime()
*/

int QTime::restart()
{
    QTime t = currentTime();
    int n = msecsTo(t);
    if (n < 0)                                // passed midnight
        n += 86400*1000;
    *this = t;
    return n;
}

/*!
    Returns the number of milliseconds that have elapsed since the
    last time start() or restart() was called.

    Note that the counter wraps to zero 24 hours after the last call
    to start() or restart.

    Note that the accuracy depends on the accuracy of the underlying
    operating system; not all systems provide 1-millisecond accuracy.

    \warning If the system's clock setting has been changed since the
    last time start() or restart() was called, the result is
    undefined. This can happen when daylight-saving time is turned on
    or off.

    \sa start(), restart()
*/

int QTime::elapsed() const
{
    int n = msecsTo(currentTime());
    if (n < 0)                                // passed midnight
        n += 86400 * 1000;
    return n;
}
#endif // Use QElapsedTimer instead !

/*****************************************************************************
  QDateTime static helper functions
 *****************************************************************************/

// get the types from QDateTime (through QDateTimePrivate)
typedef QDateTimePrivate::QDateTimeShortData ShortData;
typedef QDateTimePrivate::QDateTimeData QDateTimeData;

// Returns the platform variant of timezone, i.e. the standard time offset
// The timezone external variable is documented as always holding the
// Standard Time offset as seconds west of Greenwich, i.e. UTC+01:00 is -3600
// Note this may not be historicaly accurate.
// Relies on tzset, mktime, or localtime having been called to populate timezone
static int qt_timezone()
{
#if defined(_MSC_VER)
        long offset;
        _get_timezone(&offset);
        return offset;
#elif defined(Q_OS_BSD4) && !defined(Q_OS_DARWIN)
        time_t clock = time(NULL);
        struct tm t;
        localtime_r(&clock, &t);
        // QTBUG-36080 Workaround for systems without the POSIX timezone
        // variable. This solution is not very efficient but fixing it is up to
        // the libc implementations.
        //
        // tm_gmtoff has some important differences compared to the timezone
        // variable:
        // - It returns the number of seconds east of UTC, and we want the
        //   number of seconds west of UTC.
        // - It also takes DST into account, so we need to adjust it to always
        //   get the Standard Time offset.
        return -t.tm_gmtoff + (t.tm_isdst ? (long)SECS_PER_HOUR : 0L);
#elif defined(Q_OS_INTEGRITY) || defined(Q_OS_RTEMS)
        return 0;
#else
        return timezone;
#endif // Q_OS_WIN
}

// Returns the tzname, assume tzset has been called already
static QString qt_tzname(QDateTimePrivate::DaylightStatus daylightStatus)
{
    int isDst = (daylightStatus == QDateTimePrivate::DaylightTime) ? 1 : 0;
#if defined(Q_CC_MSVC)
    size_t s = 0;
    char name[512];
    if (_get_tzname(&s, name, 512, isDst))
        return QString();
    return QString::fromLocal8Bit(name);
#else
    return QString::fromLocal8Bit(tzname[isDst]);
#endif // Q_OS_WIN
}

#if QT_CONFIG(datetimeparser) && QT_CONFIG(timezone)
/*
  \internal
  Implemented here to share qt_tzname()
*/
int QDateTimeParser::startsWithLocalTimeZone(const QStringRef name)
{
    QDateTimePrivate::DaylightStatus zones[2] = {
        QDateTimePrivate::StandardTime,
        QDateTimePrivate::DaylightTime
    };
    for (const auto z : zones) {
        QString zone(qt_tzname(z));
        if (name.startsWith(zone))
            return zone.size();
    }
    return 0;
}
#endif // datetimeparser && timezone

// Calls the platform variant of mktime for the given date, time and daylightStatus,
// and updates the date, time, daylightStatus and abbreviation with the returned values
// If the date falls outside the 1970 to 2037 range supported by mktime / time_t
// then null date/time will be returned, you should adjust the date first if
// you need a guaranteed result.
static qint64 qt_mktime(QDate *date, QTime *time, QDateTimePrivate::DaylightStatus *daylightStatus,
                        QString *abbreviation, bool *ok = nullptr)
{
    const qint64 msec = time->msec();
    int yy, mm, dd;
    date->getDate(&yy, &mm, &dd);

    // All other platforms provide standard C library time functions
    tm local;
    memset(&local, 0, sizeof(local)); // tm_[wy]day plus any non-standard fields
    local.tm_sec = time->second();
    local.tm_min = time->minute();
    local.tm_hour = time->hour();
    local.tm_mday = dd;
    local.tm_mon = mm - 1;
    local.tm_year = yy - 1900;
    if (daylightStatus)
        local.tm_isdst = int(*daylightStatus);
    else
        local.tm_isdst = -1;

#if defined(Q_OS_WIN)
    int hh = local.tm_hour;
#endif // Q_OS_WIN
    time_t secsSinceEpoch = qMkTime(&local);
    if (secsSinceEpoch != time_t(-1)) {
        *date = QDate(local.tm_year + 1900, local.tm_mon + 1, local.tm_mday);
        *time = QTime(local.tm_hour, local.tm_min, local.tm_sec, msec);
#if defined(Q_OS_WIN)
        // Windows mktime for the missing hour subtracts 1 hour from the time
        // instead of adding 1 hour.  If time differs and is standard time then
        // this has happened, so add 2 hours to the time and 1 hour to the msecs
        if (local.tm_isdst == 0 && local.tm_hour != hh) {
            if (time->hour() >= 22)
                *date = date->addDays(1);
            *time = time->addSecs(2 * SECS_PER_HOUR);
            secsSinceEpoch += SECS_PER_HOUR;
            local.tm_isdst = 1;
        }
#endif // Q_OS_WIN
        if (local.tm_isdst >= 1) {
            if (daylightStatus)
                *daylightStatus = QDateTimePrivate::DaylightTime;
            if (abbreviation)
                *abbreviation = qt_tzname(QDateTimePrivate::DaylightTime);
        } else if (local.tm_isdst == 0) {
            if (daylightStatus)
                *daylightStatus = QDateTimePrivate::StandardTime;
            if (abbreviation)
                *abbreviation = qt_tzname(QDateTimePrivate::StandardTime);
        } else {
            if (daylightStatus)
                *daylightStatus = QDateTimePrivate::UnknownDaylightTime;
            if (abbreviation)
                *abbreviation = qt_tzname(QDateTimePrivate::StandardTime);
        }
        if (ok)
            *ok = true;
    } else {
        *date = QDate();
        *time = QTime();
        if (daylightStatus)
            *daylightStatus = QDateTimePrivate::UnknownDaylightTime;
        if (abbreviation)
            *abbreviation = QString();
        if (ok)
            *ok = false;
    }

    return ((qint64)secsSinceEpoch * 1000) + msec;
}

// Calls the platform variant of localtime for the given msecs, and updates
// the date, time, and DST status with the returned values.
static bool qt_localtime(qint64 msecsSinceEpoch, QDate *localDate, QTime *localTime,
                         QDateTimePrivate::DaylightStatus *daylightStatus)
{
    const time_t secsSinceEpoch = msecsSinceEpoch / 1000;
    const int msec = msecsSinceEpoch % 1000;

    tm local;
    bool valid = false;

    // localtime() is specified to work as if it called tzset().
    // localtime_r() does not have this constraint, so make an explicit call.
    // The explicit call should also request the timezone info be re-parsed.
    qTzSet();
#if QT_CONFIG(thread) && defined(_POSIX_THREAD_SAFE_FUNCTIONS)
    // Use the reentrant version of localtime() where available
    // as is thread-safe and doesn't use a shared static data area
    tm *res = nullptr;
    res = localtime_r(&secsSinceEpoch, &local);
    if (res)
        valid = true;
#elif defined(Q_CC_MSVC)
    if (!_localtime64_s(&local, &secsSinceEpoch))
        valid = true;
#else
    // Returns shared static data which may be overwritten at any time
    // So copy the result asap
    tm *res = nullptr;
    res = localtime(&secsSinceEpoch);
    if (res) {
        local = *res;
        valid = true;
    }
#endif
    if (valid) {
        *localDate = QDate(local.tm_year + 1900, local.tm_mon + 1, local.tm_mday);
        *localTime = QTime(local.tm_hour, local.tm_min, local.tm_sec, msec);
        if (daylightStatus) {
            if (local.tm_isdst > 0)
                *daylightStatus = QDateTimePrivate::DaylightTime;
            else if (local.tm_isdst < 0)
                *daylightStatus = QDateTimePrivate::UnknownDaylightTime;
            else
                *daylightStatus = QDateTimePrivate::StandardTime;
        }
        return true;
    } else {
        *localDate = QDate();
        *localTime = QTime();
        if (daylightStatus)
            *daylightStatus = QDateTimePrivate::UnknownDaylightTime;
        return false;
    }
}

// Converts an msecs value into a date and time
static void msecsToTime(qint64 msecs, QDate *date, QTime *time)
{
    qint64 jd = JULIAN_DAY_FOR_EPOCH;
    qint64 ds = 0;

    if (msecs >= MSECS_PER_DAY || msecs <= -MSECS_PER_DAY) {
        jd += msecs / MSECS_PER_DAY;
        msecs %= MSECS_PER_DAY;
    }

    if (msecs < 0) {
        ds = MSECS_PER_DAY - msecs - 1;
        jd -= ds / MSECS_PER_DAY;
        ds = ds % MSECS_PER_DAY;
        ds = MSECS_PER_DAY - ds - 1;
    } else {
        ds = msecs;
    }

    if (date)
        *date = QDate::fromJulianDay(jd);
    if (time)
        *time = QTime::fromMSecsSinceStartOfDay(ds);
}

// Converts a date/time value into msecs
static qint64 timeToMSecs(const QDate &date, const QTime &time)
{
    return ((date.toJulianDay() - JULIAN_DAY_FOR_EPOCH) * MSECS_PER_DAY)
           + time.msecsSinceStartOfDay();
}

// Convert an MSecs Since Epoch into Local Time
static bool epochMSecsToLocalTime(qint64 msecs, QDate *localDate, QTime *localTime,
                                  QDateTimePrivate::DaylightStatus *daylightStatus = nullptr)
{
    if (msecs < 0) {
        // Docs state any LocalTime before 1970-01-01 will *not* have any Daylight Time applied
        // Instead just use the standard offset from UTC to convert to UTC time
        qTzSet();
        msecsToTime(msecs - qt_timezone() * 1000, localDate, localTime);
        if (daylightStatus)
            *daylightStatus = QDateTimePrivate::StandardTime;
        return true;
    } else if (msecs > (qint64(TIME_T_MAX) * 1000)) {
        // Docs state any LocalTime after 2037-12-31 *will* have any DST applied
        // but this may fall outside the supported time_t range, so need to fake it.
        // Use existing method to fake the conversion, but this is deeply flawed as it may
        // apply the conversion from the wrong day number, e.g. if rule is last Sunday of month
        // TODO Use QTimeZone when available to apply the future rule correctly
        QDate utcDate;
        QTime utcTime;
        msecsToTime(msecs, &utcDate, &utcTime);
        int year, month, day;
        utcDate.getDate(&year, &month, &day);
        // 2037 is not a leap year, so make sure date isn't Feb 29
        if (month == 2 && day == 29)
            --day;
        QDate fakeDate(2037, month, day);
        qint64 fakeMsecs = QDateTime(fakeDate, utcTime, Qt::UTC).toMSecsSinceEpoch();
        bool res = qt_localtime(fakeMsecs, localDate, localTime, daylightStatus);
        *localDate = localDate->addDays(fakeDate.daysTo(utcDate));
        return res;
    } else {
        // Falls inside time_t suported range so can use localtime
        return qt_localtime(msecs, localDate, localTime, daylightStatus);
    }
}

// Convert a LocalTime expressed in local msecs encoding and the corresponding
// DST status into a UTC epoch msecs. Optionally populate the returned
// values from mktime for the adjusted local date and time.
static qint64 localMSecsToEpochMSecs(qint64 localMsecs,
                                     QDateTimePrivate::DaylightStatus *daylightStatus,
                                     QDate *localDate = nullptr, QTime *localTime = nullptr,
                                     QString *abbreviation = nullptr)
{
    QDate dt;
    QTime tm;
    msecsToTime(localMsecs, &dt, &tm);

    const qint64 msecsMax = qint64(TIME_T_MAX) * 1000;

    if (localMsecs <= qint64(MSECS_PER_DAY)) {

        // Docs state any LocalTime before 1970-01-01 will *not* have any DST applied

        // First, if localMsecs is within +/- 1 day of minimum time_t try mktime in case it does
        // fall after minimum and needs proper DST conversion
        if (localMsecs >= -qint64(MSECS_PER_DAY)) {
            bool valid;
            qint64 utcMsecs = qt_mktime(&dt, &tm, daylightStatus, abbreviation, &valid);
            if (valid && utcMsecs >= 0) {
                // mktime worked and falls in valid range, so use it
                if (localDate)
                    *localDate = dt;
                if (localTime)
                    *localTime = tm;
                return utcMsecs;
            }
        } else {
            // If we don't call mktime then need to call tzset to get offset
            qTzSet();
        }
        // Time is clearly before 1970-01-01 so just use standard offset to convert
        qint64 utcMsecs = localMsecs + qt_timezone() * 1000;
        if (localDate || localTime)
            msecsToTime(localMsecs, localDate, localTime);
        if (daylightStatus)
            *daylightStatus = QDateTimePrivate::StandardTime;
        if (abbreviation)
            *abbreviation = qt_tzname(QDateTimePrivate::StandardTime);
        return utcMsecs;

    } else if (localMsecs >= msecsMax - MSECS_PER_DAY) {

        // Docs state any LocalTime after 2037-12-31 *will* have any DST applied
        // but this may fall outside the supported time_t range, so need to fake it.

        // First, if localMsecs is within +/- 1 day of maximum time_t try mktime in case it does
        // fall before maximum and can use proper DST conversion
        if (localMsecs <= msecsMax + MSECS_PER_DAY) {
            bool valid;
            qint64 utcMsecs = qt_mktime(&dt, &tm, daylightStatus, abbreviation, &valid);
            if (valid && utcMsecs <= msecsMax) {
                // mktime worked and falls in valid range, so use it
                if (localDate)
                    *localDate = dt;
                if (localTime)
                    *localTime = tm;
                return utcMsecs;
            }
        }
        // Use existing method to fake the conversion, but this is deeply flawed as it may
        // apply the conversion from the wrong day number, e.g. if rule is last Sunday of month
        // TODO Use QTimeZone when available to apply the future rule correctly
        int year, month, day;
        dt.getDate(&year, &month, &day);
        // 2037 is not a leap year, so make sure date isn't Feb 29
        if (month == 2 && day == 29)
            --day;
        QDate fakeDate(2037, month, day);
        qint64 fakeDiff = fakeDate.daysTo(dt);
        qint64 utcMsecs = qt_mktime(&fakeDate, &tm, daylightStatus, abbreviation);
        if (localDate)
            *localDate = fakeDate.addDays(fakeDiff);
        if (localTime)
            *localTime = tm;
        QDate utcDate;
        QTime utcTime;
        msecsToTime(utcMsecs, &utcDate, &utcTime);
        utcDate = utcDate.addDays(fakeDiff);
        utcMsecs = timeToMSecs(utcDate, utcTime);
        return utcMsecs;

    } else {

        // Clearly falls inside 1970-2037 suported range so can use mktime
        qint64 utcMsecs = qt_mktime(&dt, &tm, daylightStatus, abbreviation);
        if (localDate)
            *localDate = dt;
        if (localTime)
            *localTime = tm;
        return utcMsecs;

    }
}

static inline bool specCanBeSmall(Qt::TimeSpec spec)
{
    return spec == Qt::LocalTime || spec == Qt::UTC;
}

static inline bool msecsCanBeSmall(qint64 msecs)
{
    if (!QDateTimeData::CanBeSmall)
        return false;

    ShortData sd;
    sd.msecs = qintptr(msecs);
    return sd.msecs == msecs;
}

static Q_DECL_CONSTEXPR inline
QDateTimePrivate::StatusFlags mergeSpec(QDateTimePrivate::StatusFlags status, Qt::TimeSpec spec)
{
    return QDateTimePrivate::StatusFlags((status & ~QDateTimePrivate::TimeSpecMask) |
                                         (int(spec) << QDateTimePrivate::TimeSpecShift));
}

static Q_DECL_CONSTEXPR inline Qt::TimeSpec extractSpec(QDateTimePrivate::StatusFlags status)
{
    return Qt::TimeSpec((status & QDateTimePrivate::TimeSpecMask) >> QDateTimePrivate::TimeSpecShift);
}

// Set the Daylight Status if LocalTime set via msecs
static Q_DECL_RELAXED_CONSTEXPR inline QDateTimePrivate::StatusFlags
mergeDaylightStatus(QDateTimePrivate::StatusFlags sf, QDateTimePrivate::DaylightStatus status)
{
    sf &= ~QDateTimePrivate::DaylightMask;
    if (status == QDateTimePrivate::DaylightTime) {
        sf |= QDateTimePrivate::SetToDaylightTime;
    } else if (status == QDateTimePrivate::StandardTime) {
        sf |= QDateTimePrivate::SetToStandardTime;
    }
    return sf;
}

// Get the DST Status if LocalTime set via msecs
static Q_DECL_RELAXED_CONSTEXPR inline
QDateTimePrivate::DaylightStatus extractDaylightStatus(QDateTimePrivate::StatusFlags status)
{
    if (status & QDateTimePrivate::SetToDaylightTime)
        return QDateTimePrivate::DaylightTime;
    if (status & QDateTimePrivate::SetToStandardTime)
        return QDateTimePrivate::StandardTime;
    return QDateTimePrivate::UnknownDaylightTime;
}

static inline qint64 getMSecs(const QDateTimeData &d)
{
    if (d.isShort()) {
        // same as, but producing better code
        //return d.data.msecs;
        return qintptr(d.d) >> 8;
    }
    return d->m_msecs;
}

static inline QDateTimePrivate::StatusFlags getStatus(const QDateTimeData &d)
{
    if (d.isShort()) {
        // same as, but producing better code
        //return StatusFlag(d.data.status);
        return QDateTimePrivate::StatusFlag(qintptr(d.d) & 0xFF);
    }
    return d->m_status;
}

static inline Qt::TimeSpec getSpec(const QDateTimeData &d)
{
    return extractSpec(getStatus(d));
}

#if QT_CONFIG(timezone)
void QDateTimePrivate::setUtcOffsetByTZ(qint64 atMSecsSinceEpoch)
{
    m_offsetFromUtc = m_timeZone.d->offsetFromUtc(atMSecsSinceEpoch);
}
#endif

// Refresh the LocalTime validity and offset
static void refreshDateTime(QDateTimeData &d)
{
    auto status = getStatus(d);
    const auto spec = extractSpec(status);
    const qint64 msecs = getMSecs(d);
    qint64 epochMSecs = 0;
    int offsetFromUtc = 0;
    QDate testDate;
    QTime testTime;
    Q_ASSERT(spec == Qt::TimeZone || spec == Qt::LocalTime);

#if QT_CONFIG(timezone)
    // If not valid time zone then is invalid
    if (spec == Qt::TimeZone) {
        if (!d->m_timeZone.isValid()) {
            status &= ~QDateTimePrivate::ValidDateTime;
        } else {
            epochMSecs = QDateTimePrivate::zoneMSecsToEpochMSecs(msecs, d->m_timeZone, extractDaylightStatus(status), &testDate, &testTime);
            d->setUtcOffsetByTZ(epochMSecs);
        }
    }
#endif // timezone

    // If not valid date and time then is invalid
    if (!(status & QDateTimePrivate::ValidDate) || !(status & QDateTimePrivate::ValidTime)) {
        status &= ~QDateTimePrivate::ValidDateTime;
        if (status & QDateTimePrivate::ShortData) {
            d.data.status = status;
        } else {
            d->m_status = status;
            d->m_offsetFromUtc = 0;
        }
        return;
    }

    // We have a valid date and time and a Qt::LocalTime or Qt::TimeZone that needs calculating
    // LocalTime and TimeZone might fall into a "missing" DST transition hour
    // Calling toEpochMSecs will adjust the returned date/time if it does
    if (spec == Qt::LocalTime) {
        auto dstStatus = extractDaylightStatus(status);
        epochMSecs = localMSecsToEpochMSecs(msecs, &dstStatus, &testDate, &testTime);
    }
    if (timeToMSecs(testDate, testTime) == msecs) {
        status |= QDateTimePrivate::ValidDateTime;
        // Cache the offset to use in offsetFromUtc()
        offsetFromUtc = (msecs - epochMSecs) / 1000;
    } else {
        status &= ~QDateTimePrivate::ValidDateTime;
    }

    if (status & QDateTimePrivate::ShortData) {
        d.data.status = status;
    } else {
        d->m_status = status;
        d->m_offsetFromUtc = offsetFromUtc;
    }
}

// Check the UTC / offsetFromUTC validity
static void checkValidDateTime(QDateTimeData &d)
{
    auto status = getStatus(d);
    auto spec = extractSpec(status);
    switch (spec) {
    case Qt::OffsetFromUTC:
    case Qt::UTC:
        // for these, a valid date and a valid time imply a valid QDateTime
        if ((status & QDateTimePrivate::ValidDate) && (status & QDateTimePrivate::ValidTime))
            status |= QDateTimePrivate::ValidDateTime;
        else
            status &= ~QDateTimePrivate::ValidDateTime;
        if (status & QDateTimePrivate::ShortData)
            d.data.status = status;
        else
            d->m_status = status;
        break;
    case Qt::TimeZone:
    case Qt::LocalTime:
        // for these, we need to check whether the timezone is valid and whether
        // the time is valid in that timezone. Expensive, but no other option.
        refreshDateTime(d);
        break;
    }
}

static void setTimeSpec(QDateTimeData &d, Qt::TimeSpec spec, int offsetSeconds)
{
    auto status = getStatus(d);
    status &= ~(QDateTimePrivate::ValidDateTime | QDateTimePrivate::DaylightMask |
                QDateTimePrivate::TimeSpecMask);

    switch (spec) {
    case Qt::OffsetFromUTC:
        if (offsetSeconds == 0)
            spec = Qt::UTC;
        break;
    case Qt::TimeZone:
        // Use system time zone instead
        spec = Qt::LocalTime;
        Q_FALLTHROUGH();
    case Qt::UTC:
    case Qt::LocalTime:
        offsetSeconds = 0;
        break;
    }

    status = mergeSpec(status, spec);
    if (d.isShort() && offsetSeconds == 0) {
        d.data.status = status;
    } else {
        d.detach();
        d->m_status = status & ~QDateTimePrivate::ShortData;
        d->m_offsetFromUtc = offsetSeconds;
#if QT_CONFIG(timezone)
        d->m_timeZone = QTimeZone();
#endif // timezone
    }
}

static void setDateTime(QDateTimeData &d, const QDate &date, const QTime &time)
{
    // If the date is valid and the time is not we set time to 00:00:00
    QTime useTime = time;
    if (!useTime.isValid() && date.isValid())
        useTime = QTime::fromMSecsSinceStartOfDay(0);

    QDateTimePrivate::StatusFlags newStatus = { };

    // Set date value and status
    qint64 days = 0;
    if (date.isValid()) {
        days = date.toJulianDay() - JULIAN_DAY_FOR_EPOCH;
        newStatus = QDateTimePrivate::ValidDate;
    }

    // Set time value and status
    int ds = 0;
    if (useTime.isValid()) {
        ds = useTime.msecsSinceStartOfDay();
        newStatus |= QDateTimePrivate::ValidTime;
    }

    // Set msecs serial value
    qint64 msecs = (days * MSECS_PER_DAY) + ds;
    if (d.isShort()) {
        // let's see if we can keep this short
        if (msecsCanBeSmall(msecs)) {
            // yes, we can
            d.data.msecs = qintptr(msecs);
            d.data.status &= ~(QDateTimePrivate::ValidityMask | QDateTimePrivate::DaylightMask);
            d.data.status |= newStatus;
        } else {
            // nope...
            d.detach();
        }
    }
    if (!d.isShort()) {
        d.detach();
        d->m_msecs = msecs;
        d->m_status &= ~(QDateTimePrivate::ValidityMask | QDateTimePrivate::DaylightMask);
        d->m_status |= newStatus;
    }

    // Set if date and time are valid
    checkValidDateTime(d);
}

static QPair<QDate, QTime> getDateTime(const QDateTimeData &d)
{
    QPair<QDate, QTime> result;
    qint64 msecs = getMSecs(d);
    auto status = getStatus(d);
    msecsToTime(msecs, &result.first, &result.second);

    if (!status.testFlag(QDateTimePrivate::ValidDate))
        result.first = QDate();

    if (!status.testFlag(QDateTimePrivate::ValidTime))
        result.second = QTime();

    return result;
}

/*****************************************************************************
  QDateTime::Data member functions
 *****************************************************************************/

inline QDateTime::Data::Data()
{
    // default-constructed data has a special exception:
    // it can be small even if CanBeSmall == false
    // (optimization so we don't allocate memory in the default constructor)
    quintptr value = quintptr(mergeSpec(QDateTimePrivate::ShortData, Qt::LocalTime));
    d = reinterpret_cast<QDateTimePrivate *>(value);
}

inline QDateTime::Data::Data(Qt::TimeSpec spec)
{
    if (CanBeSmall && Q_LIKELY(specCanBeSmall(spec))) {
        d = reinterpret_cast<QDateTimePrivate *>(quintptr(mergeSpec(QDateTimePrivate::ShortData, spec)));
    } else {
        // the structure is too small, we need to detach
        d = new QDateTimePrivate;
        d->ref.ref();
        d->m_status = mergeSpec(nullptr, spec);
    }
}

inline QDateTime::Data::Data(const Data &other)
    : d(other.d)
{
    if (!isShort()) {
        // check if we could shrink
        if (specCanBeSmall(extractSpec(d->m_status)) && msecsCanBeSmall(d->m_msecs)) {
            ShortData sd;
            sd.msecs = qintptr(d->m_msecs);
            sd.status = d->m_status | QDateTimePrivate::ShortData;
            data = sd;
        } else {
            // no, have to keep it big
            d->ref.ref();
        }
    }
}

inline QDateTime::Data::Data(Data &&other)
    : d(other.d)
{
    // reset the other to a short state
    Data dummy;
    Q_ASSERT(dummy.isShort());
    other.d = dummy.d;
}

inline QDateTime::Data &QDateTime::Data::operator=(const Data &other)
{
    if (d == other.d)
        return *this;

    auto x = d;
    d = other.d;
    if (!other.isShort()) {
        // check if we could shrink
        if (specCanBeSmall(extractSpec(other.d->m_status)) && msecsCanBeSmall(other.d->m_msecs)) {
            ShortData sd;
            sd.msecs = qintptr(other.d->m_msecs);
            sd.status = other.d->m_status | QDateTimePrivate::ShortData;
            data = sd;
        } else {
            // no, have to keep it big
            other.d->ref.ref();
        }
    }

    if (!(quintptr(x) & QDateTimePrivate::ShortData) && !x->ref.deref())
        delete x;
    return *this;
}

inline QDateTime::Data::~Data()
{
    if (!isShort() && !d->ref.deref())
        delete d;
}

inline bool QDateTime::Data::isShort() const
{
    bool b = quintptr(d) & QDateTimePrivate::ShortData;

    // sanity check:
    Q_ASSERT(b || (d->m_status & QDateTimePrivate::ShortData) == 0);

    // even if CanBeSmall = false, we have short data for a default-constructed
    // QDateTime object. But it's unlikely.
    if (CanBeSmall)
        return Q_LIKELY(b);
    return Q_UNLIKELY(b);
}

inline void QDateTime::Data::detach()
{
    QDateTimePrivate *x;
    bool wasShort = isShort();
    if (wasShort) {
        // force enlarging
        x = new QDateTimePrivate;
        x->m_status = QDateTimePrivate::StatusFlag(data.status & ~QDateTimePrivate::ShortData);
        x->m_msecs = data.msecs;
    } else {
        if (d->ref.loadRelaxed() == 1)
            return;

        x = new QDateTimePrivate(*d);
    }

    x->ref.storeRelaxed(1);
    if (!wasShort && !d->ref.deref())
        delete d;
    d = x;
}

inline const QDateTimePrivate *QDateTime::Data::operator->() const
{
    Q_ASSERT(!isShort());
    return d;
}

inline QDateTimePrivate *QDateTime::Data::operator->()
{
    // should we attempt to detach here?
    Q_ASSERT(!isShort());
    Q_ASSERT(d->ref.loadRelaxed() == 1);
    return d;
}

/*****************************************************************************
  QDateTimePrivate member functions
 *****************************************************************************/

Q_NEVER_INLINE
QDateTime::Data QDateTimePrivate::create(const QDate &toDate, const QTime &toTime, Qt::TimeSpec toSpec,
                                         int offsetSeconds)
{
    QDateTime::Data result(toSpec);
    setTimeSpec(result, toSpec, offsetSeconds);
    setDateTime(result, toDate, toTime);
    return result;
}

#if QT_CONFIG(timezone)
inline QDateTime::Data QDateTimePrivate::create(const QDate &toDate, const QTime &toTime,
                                                const QTimeZone &toTimeZone)
{
    QDateTime::Data result(Qt::TimeZone);
    Q_ASSERT(!result.isShort());

    result.d->m_status = mergeSpec(result.d->m_status, Qt::TimeZone);
    result.d->m_timeZone = toTimeZone;
    setDateTime(result, toDate, toTime);
    return result;
}

// Convert a TimeZone time expressed in zone msecs encoding into a UTC epoch msecs
// DST transitions are disambiguated by hint.
inline qint64 QDateTimePrivate::zoneMSecsToEpochMSecs(qint64 zoneMSecs, const QTimeZone &zone,
                                                      DaylightStatus hint,
                                                      QDate *zoneDate, QTime *zoneTime)
{
    Q_ASSERT(zone.isValid());
    // Get the effective data from QTimeZone
    QTimeZonePrivate::Data data = zone.d->dataForLocalTime(zoneMSecs, int(hint));
    // Docs state any time before 1970-01-01 will *not* have any DST applied
    // but all affected times afterwards will have DST applied.
    if (data.atMSecsSinceEpoch < 0) {
        msecsToTime(zoneMSecs, zoneDate, zoneTime);
        return zoneMSecs - data.standardTimeOffset * 1000;
    } else {
        msecsToTime(data.atMSecsSinceEpoch + data.offsetFromUtc * 1000, zoneDate, zoneTime);
        return data.atMSecsSinceEpoch;
    }
}
#endif // timezone

/*****************************************************************************
  QDateTime member functions
 *****************************************************************************/

/*!
    \class QDateTime
    \inmodule QtCore
    \ingroup shared
    \reentrant
    \brief The QDateTime class provides date and time functions.


    A QDateTime object encodes a calendar date and a clock time (a
    "datetime"). It combines features of the QDate and QTime classes.
    It can read the current datetime from the system clock. It
    provides functions for comparing datetimes and for manipulating a
    datetime by adding a number of seconds, days, months, or years.

    QDateTime can describe datetimes with respect to \l{Qt::LocalTime}{local
    time}, to \l{Qt::UTC}{UTC}, to a specified \l{Qt::OffsetFromUTC}{offset from
    UTC} or to a specified \l{Qt::TimeZone}{time zone}, in conjunction with the
    QTimeZone class. For example, a time zone of "Europe/Berlin" will apply the
    daylight-saving rules as used in Germany since 1970. In contrast, an offset
    from UTC of +3600 seconds is one hour ahead of UTC (usually written in ISO
    standard notation as "UTC+01:00"), with no daylight-saving offset or
    changes. When using either local time or a specified time zone, time-zone
    transitions such as the starts and ends of daylight-saving time (DST; but
    see below) are taken into account. The choice of system used to represent a
    datetime is described as its "timespec".

    A QDateTime object is typically created either by giving a date and time
    explicitly in the constructor, or by using a static function such as
    currentDateTime() or fromMSecsSinceEpoch(). The date and time can be changed
    with setDate() and setTime(). A datetime can also be set using the
    setMSecsSinceEpoch() function that takes the time, in milliseconds, since
    00:00:00 on January 1, 1970. The fromString() function returns a QDateTime,
    given a string and a date format used to interpret the date within the
    string.

    QDateTime::currentDateTime() returns a QDateTime that expresses the current
    time with respect to local time. QDateTime::currentDateTimeUtc() returns a
    QDateTime that expresses the current time with respect to UTC.

    The date() and time() functions provide access to the date and
    time parts of the datetime. The same information is provided in
    textual format by the toString() function.

    QDateTime provides a full set of operators to compare two
    QDateTime objects, where smaller means earlier and larger means
    later.

    You can increment (or decrement) a datetime by a given number of
    milliseconds using addMSecs(), seconds using addSecs(), or days using
    addDays(). Similarly, you can use addMonths() and addYears(). The daysTo()
    function returns the number of days between two datetimes, secsTo() returns
    the number of seconds between two datetimes, and msecsTo() returns the
    number of milliseconds between two datetimes. These operations are aware of
    daylight-saving time (DST) and other time-zone transitions, where
    applicable.

    Use toTimeSpec() to express a datetime in local time or UTC,
    toOffsetFromUtc() to express in terms of an offset from UTC, or toTimeZone()
    to express it with respect to a general time zone. You can use timeSpec() to
    find out what time-spec a QDateTime object stores its time relative to. When
    that is Qt::TimeZone, you can use timeZone() to find out which zone it is
    using.

    \note QDateTime does not account for leap seconds.

    \section1 Remarks

    \section2 No Year 0

    There is no year 0. Dates in that year are considered invalid. The
    year -1 is the year "1 before Christ" or "1 before current era."
    The day before 1 January 1 CE is 31 December 1 BCE.

    \section2 Range of Valid Dates

    The range of values that QDateTime can represent is dependent on the
    internal storage implementation. QDateTime is currently stored in a qint64
    as a serial msecs value encoding the date and time. This restricts the date
    range to about +/- 292 million years, compared to the QDate range of +/- 2
    billion years. Care must be taken when creating a QDateTime with extreme
    values that you do not overflow the storage. The exact range of supported
    values varies depending on the Qt::TimeSpec and time zone.

    \section2 Use of Timezones

    QDateTime uses the system's time zone information to determine the current
    local time zone and its offset from UTC. If the system is not configured
    correctly or not up-to-date, QDateTime will give wrong results.

    QDateTime likewise uses system-provided information to determine the offsets
    of other timezones from UTC. If this information is incomplete or out of
    date, QDateTime will give wrong results. See the QTimeZone documentation for
    more details.

    On modern Unix systems, this means QDateTime usually has accurate
    information about historical transitions (including DST, see below) whenever
    possible. On Windows, where the system doesn't support historical timezone
    data, historical accuracy is not maintained with respect to timezone
    transitions, notably including DST.

    \section2 Daylight-Saving Time (DST)

    QDateTime takes into account transitions between Standard Time and
    Daylight-Saving Time. For example, if the transition is at 2am and the clock
    goes forward to 3am, then there is a "missing" hour from 02:00:00 to
    02:59:59.999 which QDateTime considers to be invalid. Any date arithmetic
    performed will take this missing hour into account and return a valid
    result. For example, adding one minute to 01:59:59 will get 03:00:00.

    The range of valid dates taking DST into account is 1970-01-01 to the
    present, and rules are in place for handling DST correctly until 2037-12-31,
    but these could change. For dates after 2037, QDateTime makes a \e{best
    guess} using the rules for year 2037, but we can't guarantee accuracy;
    indeed, for \e{any} future date, the time-zone may change its rules before
    that date comes around. For dates before 1970, QDateTime doesn't take DST
    changes into account, even if the system's time zone database provides that
    information, although it does take into account changes to the time-zone's
    standard offset, where this information is available.

    \section2 Offsets From UTC

    There is no explicit size restriction on an offset from UTC, but there is an
    implicit limit imposed when using the toString() and fromString() methods
    which use a [+|-]hh:mm format, effectively limiting the range to +/- 99
    hours and 59 minutes and whole minutes only. Note that currently no time
    zone lies outside the range of +/- 14 hours.

    \sa QDate, QTime, QDateTimeEdit, QTimeZone
*/

/*!
    \since 5.14
    \enum QDateTime::YearRange

    This enumerated type describes the range of years (in the Gregorian
    calendar) representable by QDateTime:

    \value First The later parts of this year are representable
    \value Last The earlier parts of this year are representable

    All dates strictly between these two years are also representable.
    Note, however, that the Gregorian Calendar has no year zero.

    \note QDate can describe dates in a wider range of years.  For most
    purposes, this makes little difference, as the range of years that QDateTime
    can support reaches 292 million years either side of 1970.

    \sa isValid(), QDate
*/

/*!
    Constructs a null datetime (i.e. null date and null time). A null
    datetime is invalid, since the date is invalid.

    \sa isValid()
*/
QDateTime::QDateTime() noexcept(Data::CanBeSmall)
{
}


/*!
    Constructs a datetime with the given \a date, a valid
    time(00:00:00.000), and sets the timeSpec() to Qt::LocalTime.
*/

QDateTime::QDateTime(const QDate &date)
    : d(QDateTimePrivate::create(date, QTime(0, 0), Qt::LocalTime, 0))
{
}

/*!
    Constructs a datetime with the given \a date and \a time, using
    the time specification defined by \a spec.

    If \a date is valid and \a time is not, the time will be set to midnight.

    If \a spec is Qt::OffsetFromUTC then it will be set to Qt::UTC, i.e. an
    offset of 0 seconds. To create a Qt::OffsetFromUTC datetime use the
    correct constructor.

    If \a spec is Qt::TimeZone then the spec will be set to Qt::LocalTime,
    i.e. the current system time zone.  To create a Qt::TimeZone datetime
    use the correct constructor.
*/

QDateTime::QDateTime(const QDate &date, const QTime &time, Qt::TimeSpec spec)
    : d(QDateTimePrivate::create(date, time, spec, 0))
{
}

/*!
    \since 5.2

    Constructs a datetime with the given \a date and \a time, using
    the time specification defined by \a spec and \a offsetSeconds seconds.

    If \a date is valid and \a time is not, the time will be set to midnight.

    If the \a spec is not Qt::OffsetFromUTC then \a offsetSeconds will be ignored.

    If the \a spec is Qt::OffsetFromUTC and \a offsetSeconds is 0 then the
    timeSpec() will be set to Qt::UTC, i.e. an offset of 0 seconds.

    If \a spec is Qt::TimeZone then the spec will be set to Qt::LocalTime,
    i.e. the current system time zone.  To create a Qt::TimeZone datetime
    use the correct constructor.
*/

QDateTime::QDateTime(const QDate &date, const QTime &time, Qt::TimeSpec spec, int offsetSeconds)
         : d(QDateTimePrivate::create(date, time, spec, offsetSeconds))
{
}

#if QT_CONFIG(timezone)
/*!
    \since 5.2

    Constructs a datetime with the given \a date and \a time, using
    the Time Zone specified by \a timeZone.

    If \a date is valid and \a time is not, the time will be set to 00:00:00.

    If \a timeZone is invalid then the datetime will be invalid.
*/

QDateTime::QDateTime(const QDate &date, const QTime &time, const QTimeZone &timeZone)
    : d(QDateTimePrivate::create(date, time, timeZone))
{
}
#endif // timezone

/*!
    Constructs a copy of the \a other datetime.
*/
QDateTime::QDateTime(const QDateTime &other) noexcept
    : d(other.d)
{
}

/*!
    \since 5.8
    Moves the content of the temporary \a other datetime to this object and
    leaves \a other in an unspecified (but proper) state.
*/
QDateTime::QDateTime(QDateTime &&other) noexcept
    : d(std::move(other.d))
{
}

/*!
    Destroys the datetime.
*/
QDateTime::~QDateTime()
{
}

/*!
    Makes a copy of the \a other datetime and returns a reference to the
    copy.
*/

QDateTime &QDateTime::operator=(const QDateTime &other) noexcept
{
    d = other.d;
    return *this;
}
/*!
    \fn void QDateTime::swap(QDateTime &other)
    \since 5.0

    Swaps this datetime with \a other. This operation is very fast
    and never fails.
*/

/*!
    Returns \c true if both the date and the time are null; otherwise
    returns \c false. A null datetime is invalid.

    \sa QDate::isNull(), QTime::isNull(), isValid()
*/

bool QDateTime::isNull() const
{
    auto status = getStatus(d);
    return !status.testFlag(QDateTimePrivate::ValidDate) &&
            !status.testFlag(QDateTimePrivate::ValidTime);
}

/*!
    Returns \c true if both the date and the time are valid and they are valid in
    the current Qt::TimeSpec, otherwise returns \c false.

    If the timeSpec() is Qt::LocalTime or Qt::TimeZone then the date and time are
    checked to see if they fall in the Standard Time to Daylight-Saving Time transition
    hour, i.e. if the transition is at 2am and the clock goes forward to 3am
    then the time from 02:00:00 to 02:59:59.999 is considered to be invalid.

    \sa QDateTime::YearRange, QDate::isValid(), QTime::isValid()
*/

bool QDateTime::isValid() const
{
    auto status = getStatus(d);
    return status & QDateTimePrivate::ValidDateTime;
}

/*!
    Returns the date part of the datetime.

    \sa setDate(), time(), timeSpec()
*/

QDate QDateTime::date() const
{
    auto status = getStatus(d);
    if (!status.testFlag(QDateTimePrivate::ValidDate))
        return QDate();
    QDate dt;
    msecsToTime(getMSecs(d), &dt, nullptr);
    return dt;
}

/*!
    Returns the time part of the datetime.

    \sa setTime(), date(), timeSpec()
*/

QTime QDateTime::time() const
{
    auto status = getStatus(d);
    if (!status.testFlag(QDateTimePrivate::ValidTime))
        return QTime();
    QTime tm;
    msecsToTime(getMSecs(d), nullptr, &tm);
    return tm;
}

/*!
    Returns the time specification of the datetime.

    \sa setTimeSpec(), date(), time(), Qt::TimeSpec
*/

Qt::TimeSpec QDateTime::timeSpec() const
{
    return getSpec(d);
}

#if QT_CONFIG(timezone)
/*!
    \since 5.2

    Returns the time zone of the datetime.

    If the timeSpec() is Qt::LocalTime then an instance of the current system
    time zone will be returned. Note however that if you copy this time zone
    the instance will not remain in sync if the system time zone changes.

    \sa setTimeZone(), Qt::TimeSpec
*/

QTimeZone QDateTime::timeZone() const
{
    switch (getSpec(d)) {
    case Qt::UTC:
        return QTimeZone::utc();
    case Qt::OffsetFromUTC:
        return QTimeZone(d->m_offsetFromUtc);
    case Qt::TimeZone:
        if (d->m_timeZone.isValid())
            return d->m_timeZone;
        break;
    case Qt::LocalTime:
        return QTimeZone::systemTimeZone();
    }
    return QTimeZone();
}
#endif // timezone

/*!
    \since 5.2

    Returns this date-time's Offset From UTC in seconds.

    The result depends on timeSpec():
    \list
    \li \c Qt::UTC The offset is 0.
    \li \c Qt::OffsetFromUTC The offset is the value originally set.
    \li \c Qt::LocalTime The local time's offset from UTC is returned.
    \li \c Qt::TimeZone The offset used by the time-zone is returned.
    \endlist

    For the last two, the offset at this date and time will be returned, taking
    account of Daylight-Saving Offset unless the date precedes the start of
    1970. The offset is the difference between the local time or time in the
    given time-zone and UTC time; it is positive in time-zones ahead of UTC
    (East of The Prime Meridian), negative for those behind UTC (West of The
    Prime Meridian).

    \sa setOffsetFromUtc()
*/

int QDateTime::offsetFromUtc() const
{
    if (!d.isShort())
        return d->m_offsetFromUtc;
    if (!isValid())
        return 0;

    auto spec = getSpec(d);
    if (spec == Qt::LocalTime) {
        // we didn't cache the value, so we need to calculate it now...
        qint64 msecs = getMSecs(d);
        return (msecs - toMSecsSinceEpoch()) / 1000;
    }

    Q_ASSERT(spec == Qt::UTC);
    return 0;
}

/*!
    \since 5.2

    Returns the Time Zone Abbreviation for the datetime.

    If the timeSpec() is Qt::UTC this will be "UTC".

    If the timeSpec() is Qt::OffsetFromUTC this will be in the format
    "UTC[+-]00:00".

    If the timeSpec() is Qt::LocalTime then the host system is queried for the
    correct abbreviation.

    Note that abbreviations may or may not be localized.

    Note too that the abbreviation is not guaranteed to be a unique value,
    i.e. different time zones may have the same abbreviation.

    \sa timeSpec()
*/

QString QDateTime::timeZoneAbbreviation() const
{
    if (!isValid())
        return QString();

    switch (getSpec(d)) {
    case Qt::UTC:
        return QLatin1String("UTC");
    case Qt::OffsetFromUTC:
        return QLatin1String("UTC") + toOffsetString(Qt::ISODate, d->m_offsetFromUtc);
    case Qt::TimeZone:
#if !QT_CONFIG(timezone)
        break;
#else
        Q_ASSERT(d->m_timeZone.isValid());
        return d->m_timeZone.d->abbreviation(toMSecsSinceEpoch());
#endif // timezone
    case Qt::LocalTime:  {
        QString abbrev;
        auto status = extractDaylightStatus(getStatus(d));
        localMSecsToEpochMSecs(getMSecs(d), &status, nullptr, nullptr, &abbrev);
        return abbrev;
        }
    }
    return QString();
}

/*!
    \since 5.2

    Returns if this datetime falls in Daylight-Saving Time.

    If the Qt::TimeSpec is not Qt::LocalTime or Qt::TimeZone then will always
    return false.

    \sa timeSpec()
*/

bool QDateTime::isDaylightTime() const
{
    if (!isValid())
        return false;

    switch (getSpec(d)) {
    case Qt::UTC:
    case Qt::OffsetFromUTC:
        return false;
    case Qt::TimeZone:
#if !QT_CONFIG(timezone)
        break;
#else
        Q_ASSERT(d->m_timeZone.isValid());
        return d->m_timeZone.d->isDaylightTime(toMSecsSinceEpoch());
#endif // timezone
    case Qt::LocalTime: {
        auto status = extractDaylightStatus(getStatus(d));
        if (status == QDateTimePrivate::UnknownDaylightTime)
            localMSecsToEpochMSecs(getMSecs(d), &status);
        return (status == QDateTimePrivate::DaylightTime);
        }
    }
    return false;
}

/*!
    Sets the date part of this datetime to \a date. If no time is set yet, it
    is set to midnight. If \a date is invalid, this QDateTime becomes invalid.

    \sa date(), setTime(), setTimeSpec()
*/

void QDateTime::setDate(const QDate &date)
{
    setDateTime(d, date, time());
}

/*!
    Sets the time part of this datetime to \a time. If \a time is not valid,
    this function sets it to midnight. Therefore, it's possible to clear any
    set time in a QDateTime by setting it to a default QTime:

    \code
        QDateTime dt = QDateTime::currentDateTime();
        dt.setTime(QTime());
    \endcode

    \sa time(), setDate(), setTimeSpec()
*/

void QDateTime::setTime(const QTime &time)
{
    setDateTime(d, date(), time);
}

/*!
    Sets the time specification used in this datetime to \a spec.
    The datetime will refer to a different point in time.

    If \a spec is Qt::OffsetFromUTC then the timeSpec() will be set
    to Qt::UTC, i.e. an effective offset of 0.

    If \a spec is Qt::TimeZone then the spec will be set to Qt::LocalTime,
    i.e. the current system time zone.

    Example:
    \snippet code/src_corelib_tools_qdatetime.cpp 19

    \sa timeSpec(), setDate(), setTime(), setTimeZone(), Qt::TimeSpec
*/

void QDateTime::setTimeSpec(Qt::TimeSpec spec)
{
    QT_PREPEND_NAMESPACE(setTimeSpec(d, spec, 0));
    checkValidDateTime(d);
}

/*!
    \since 5.2

    Sets the timeSpec() to Qt::OffsetFromUTC and the offset to \a offsetSeconds.
    The datetime will refer to a different point in time.

    The maximum and minimum offset is 14 positive or negative hours.  If
    \a offsetSeconds is larger or smaller than that, then the result is
    undefined.

    If \a offsetSeconds is 0 then the timeSpec() will be set to Qt::UTC.

    \sa isValid(), offsetFromUtc()
*/

void QDateTime::setOffsetFromUtc(int offsetSeconds)
{
    QT_PREPEND_NAMESPACE(setTimeSpec(d, Qt::OffsetFromUTC, offsetSeconds));
    checkValidDateTime(d);
}

#if QT_CONFIG(timezone)
/*!
    \since 5.2

    Sets the time zone used in this datetime to \a toZone.
    The datetime will refer to a different point in time.

    If \a toZone is invalid then the datetime will be invalid.

    \sa timeZone(), Qt::TimeSpec
*/

void QDateTime::setTimeZone(const QTimeZone &toZone)
{
    d.detach();         // always detach
    d->m_status = mergeSpec(d->m_status, Qt::TimeZone);
    d->m_offsetFromUtc = 0;
    d->m_timeZone = toZone;
    refreshDateTime(d);
}
#endif // timezone

/*!
    \since 4.7

    Returns the datetime as the number of milliseconds that have passed
    since 1970-01-01T00:00:00.000, Coordinated Universal Time (Qt::UTC).

    On systems that do not support time zones, this function will
    behave as if local time were Qt::UTC.

    The behavior for this function is undefined if the datetime stored in
    this object is not valid. However, for all valid dates, this function
    returns a unique value.

    \sa toSecsSinceEpoch(), setMSecsSinceEpoch()
*/
qint64 QDateTime::toMSecsSinceEpoch() const
{
    // Note: QDateTimeParser relies on this producing a useful result, even when
    // !isValid(), at least when the invalidity is a time in a fall-back (that
    // we'll have adjusted to lie outside it, but marked invalid because it's
    // not what was asked for). Other things may be doing similar.
    switch (getSpec(d)) {
    case Qt::UTC:
        return getMSecs(d);

    case Qt::OffsetFromUTC:
        return d->m_msecs - (d->m_offsetFromUtc * 1000);

    case Qt::LocalTime: {
        // recalculate the local timezone
        auto status = extractDaylightStatus(getStatus(d));
        return localMSecsToEpochMSecs(getMSecs(d), &status);
    }

    case Qt::TimeZone:
#if QT_CONFIG(timezone)
        if (d->m_timeZone.isValid()) {
            return QDateTimePrivate::zoneMSecsToEpochMSecs(d->m_msecs, d->m_timeZone,
                                                           extractDaylightStatus(getStatus(d)));
        }
#endif
        return 0;
    }
    Q_UNREACHABLE();
    return 0;
}

/*!
    \since 5.8

    Returns the datetime as the number of seconds that have passed since
    1970-01-01T00:00:00.000, Coordinated Universal Time (Qt::UTC).

    On systems that do not support time zones, this function will
    behave as if local time were Qt::UTC.

    The behavior for this function is undefined if the datetime stored in
    this object is not valid. However, for all valid dates, this function
    returns a unique value.

    \sa toMSecsSinceEpoch(), setSecsSinceEpoch()
*/
qint64 QDateTime::toSecsSinceEpoch() const
{
    return toMSecsSinceEpoch() / 1000;
}

#if QT_DEPRECATED_SINCE(5, 8)
/*!
    \deprecated

    Returns the datetime as the number of seconds that have passed
    since 1970-01-01T00:00:00, Coordinated Universal Time (Qt::UTC).

    On systems that do not support time zones, this function will
    behave as if local time were Qt::UTC.

    \note This function returns a 32-bit unsigned integer and is deprecated.

    If the date is outside the range 1970-01-01T00:00:00 to
    2106-02-07T06:28:14, this function returns -1 cast to an unsigned integer
    (i.e., 0xFFFFFFFF).

    To get an extended range, use toMSecsSinceEpoch() or toSecsSinceEpoch().

    \sa toSecsSinceEpoch(), toMSecsSinceEpoch(), setTime_t()
*/

uint QDateTime::toTime_t() const
{
    if (!isValid())
        return uint(-1);
    qint64 retval = toMSecsSinceEpoch() / 1000;
    if (quint64(retval) >= Q_UINT64_C(0xFFFFFFFF))
        return uint(-1);
    return uint(retval);
}
#endif

/*!
    \since 4.7

    Sets the date and time given the number of milliseconds \a msecs that have
    passed since 1970-01-01T00:00:00.000, Coordinated Universal Time
    (Qt::UTC). On systems that do not support time zones this function
    will behave as if local time were Qt::UTC.

    Note that passing the minimum of \c qint64
    (\c{std::numeric_limits<qint64>::min()}) to \a msecs will result in
    undefined behavior.

    \sa toMSecsSinceEpoch(), setSecsSinceEpoch()
*/
void QDateTime::setMSecsSinceEpoch(qint64 msecs)
{
    const auto spec = getSpec(d);
    auto status = getStatus(d);

    status &= ~QDateTimePrivate::ValidityMask;
    switch (spec) {
    case Qt::UTC:
        status = status
                    | QDateTimePrivate::ValidDate
                    | QDateTimePrivate::ValidTime
                    | QDateTimePrivate::ValidDateTime;
        break;
    case Qt::OffsetFromUTC:
        msecs = msecs + (d->m_offsetFromUtc * 1000);
        status = status
                    | QDateTimePrivate::ValidDate
                    | QDateTimePrivate::ValidTime
                    | QDateTimePrivate::ValidDateTime;
        break;
    case Qt::TimeZone:
        Q_ASSERT(!d.isShort());
#if QT_CONFIG(timezone)
        d.detach();
        if (!d->m_timeZone.isValid())
            break;
        // Docs state any LocalTime before 1970-01-01 will *not* have any DST applied
        // but all affected times afterwards will have DST applied.
        if (msecs >= 0) {
            status = mergeDaylightStatus(status,
                                         d->m_timeZone.d->isDaylightTime(msecs)
                                         ? QDateTimePrivate::DaylightTime
                                         : QDateTimePrivate::StandardTime);
            d->m_offsetFromUtc = d->m_timeZone.d->offsetFromUtc(msecs);
        } else {
            status = mergeDaylightStatus(status, QDateTimePrivate::StandardTime);
            d->m_offsetFromUtc = d->m_timeZone.d->standardTimeOffset(msecs);
        }
        msecs = msecs + (d->m_offsetFromUtc * 1000);
        status = status
                    | QDateTimePrivate::ValidDate
                    | QDateTimePrivate::ValidTime
                    | QDateTimePrivate::ValidDateTime;
#endif // timezone
        break;
    case Qt::LocalTime: {
        QDate dt;
        QTime tm;
        QDateTimePrivate::DaylightStatus dstStatus;
        epochMSecsToLocalTime(msecs, &dt, &tm, &dstStatus);
        setDateTime(d, dt, tm);
        msecs = getMSecs(d);
        status = mergeDaylightStatus(getStatus(d), dstStatus);
        break;
        }
    }

    if (msecsCanBeSmall(msecs) && d.isShort()) {
        // we can keep short
        d.data.msecs = qintptr(msecs);
        d.data.status = status;
    } else {
        d.detach();
        d->m_status = status & ~QDateTimePrivate::ShortData;
        d->m_msecs = msecs;
    }

    if (spec == Qt::LocalTime || spec == Qt::TimeZone)
        refreshDateTime(d);
}

/*!
    \since 5.8

    Sets the date and time given the number of seconds \a secs that have
    passed since 1970-01-01T00:00:00.000, Coordinated Universal Time
    (Qt::UTC). On systems that do not support time zones this function
    will behave as if local time were Qt::UTC.

    \sa toSecsSinceEpoch(), setMSecsSinceEpoch()
*/
void QDateTime::setSecsSinceEpoch(qint64 secs)
{
    setMSecsSinceEpoch(secs * 1000);
}

#if QT_DEPRECATED_SINCE(5, 8)
/*!
    \fn void QDateTime::setTime_t(uint seconds)
    \deprecated

    Sets the date and time given the number of \a seconds that have
    passed since 1970-01-01T00:00:00, Coordinated Universal Time
    (Qt::UTC). On systems that do not support time zones this function
    will behave as if local time were Qt::UTC.

    \note This function is deprecated. For new code, use setSecsSinceEpoch().

    \sa toTime_t()
*/

void QDateTime::setTime_t(uint secsSince1Jan1970UTC)
{
    setMSecsSinceEpoch((qint64)secsSince1Jan1970UTC * 1000);
}
#endif

#if QT_CONFIG(datestring) // depends on, so implies, textdate
/*!
    \fn QString QDateTime::toString(Qt::DateFormat format) const

    \overload

    Returns the datetime as a string in the \a format given.

    If the \a format is Qt::TextDate, the string is formatted in the default
    way. The day and month names will be localized names using the system
    locale, i.e. QLocale::system(). An example of this formatting is "Wed May 20
    03:40:13 1998".

    If the \a format is Qt::ISODate, the string format corresponds
    to the ISO 8601 extended specification for representations of
    dates and times, taking the form yyyy-MM-ddTHH:mm:ss[Z|[+|-]HH:mm],
    depending on the timeSpec() of the QDateTime. If the timeSpec()
    is Qt::UTC, Z will be appended to the string; if the timeSpec() is
    Qt::OffsetFromUTC, the offset in hours and minutes from UTC will
    be appended to the string. To include milliseconds in the ISO 8601
    date, use the \a format Qt::ISODateWithMs, which corresponds to
    yyyy-MM-ddTHH:mm:ss.zzz[Z|[+|-]HH:mm].

    If the \a format is Qt::SystemLocaleShortDate or
    Qt::SystemLocaleLongDate, the string format depends on the locale
    settings of the system. Identical to calling
    QLocale::system().toString(datetime, QLocale::ShortFormat) or
    QLocale::system().toString(datetime, QLocale::LongFormat).

    If the \a format is Qt::DefaultLocaleShortDate or
    Qt::DefaultLocaleLongDate, the string format depends on the
    default application locale. This is the locale set with
    QLocale::setDefault(), or the system locale if no default locale
    has been set. Identical to calling QLocale().toString(datetime,
    QLocale::ShortFormat) or QLocale().toString(datetime,
    QLocale::LongFormat).

    If the \a format is Qt::RFC2822Date, the string is formatted
    following \l{RFC 2822}.

    If the datetime is invalid, an empty string will be returned.

    \warning The Qt::ISODate format is only valid for years in the
    range 0 to 9999. This restriction may apply to locale-aware
    formats as well, depending on the locale settings.

    \sa fromString(), QDate::toString(), QTime::toString(),
    QLocale::toString()
*/

QString QDateTime::toString(Qt::DateFormat format) const
{
    QString buf;
    if (!isValid())
        return buf;

    switch (format) {
    case Qt::SystemLocaleDate:
    case Qt::SystemLocaleShortDate:
        return QLocale::system().toString(*this, QLocale::ShortFormat);
    case Qt::SystemLocaleLongDate:
        return QLocale::system().toString(*this, QLocale::LongFormat);
    case Qt::LocaleDate:
    case Qt::DefaultLocaleShortDate:
        return QLocale().toString(*this, QLocale::ShortFormat);
    case Qt::DefaultLocaleLongDate:
        return QLocale().toString(*this, QLocale::LongFormat);
    case Qt::RFC2822Date: {
        buf = QLocale::c().toString(*this, u"dd MMM yyyy hh:mm:ss ");
        buf += toOffsetString(Qt::TextDate, offsetFromUtc());
        return buf;
    }
    default:
    case Qt::TextDate: {
        const QPair<QDate, QTime> p = getDateTime(d);
        buf = p.first.toString(Qt::TextDate);
        // Insert time between date's day and year:
        buf.insert(buf.lastIndexOf(QLatin1Char(' ')),
                   QLatin1Char(' ') + p.second.toString(Qt::TextDate));
        // Append zone/offset indicator, as appropriate:
        switch (timeSpec()) {
        case Qt::LocalTime:
            break;
#if QT_CONFIG(timezone)
        case Qt::TimeZone:
            buf += QLatin1Char(' ') + d->m_timeZone.abbreviation(*this);
            break;
#endif
        default:
            buf += QLatin1String(" GMT");
            if (getSpec(d) == Qt::OffsetFromUTC)
                buf += toOffsetString(Qt::TextDate, offsetFromUtc());
        }
        return buf;
    }
    case Qt::ISODate:
    case Qt::ISODateWithMs: {
        const QPair<QDate, QTime> p = getDateTime(d);
        const QDate &dt = p.first;
        const QTime &tm = p.second;
        buf = dt.toString(Qt::ISODate);
        if (buf.isEmpty())
            return QString();   // failed to convert
        buf += QLatin1Char('T');
        buf += tm.toString(format);
        switch (getSpec(d)) {
        case Qt::UTC:
            buf += QLatin1Char('Z');
            break;
        case Qt::OffsetFromUTC:
#if QT_CONFIG(timezone)
        case Qt::TimeZone:
#endif
            buf += toOffsetString(Qt::ISODate, offsetFromUtc());
            break;
        default:
            break;
        }
        return buf;
    }
    }
}

/*!
    \fn QString QDateTime::toString(const QString &format) const
    \fn QString QDateTime::toString(QStringView format) const

    Returns the datetime as a string. The \a format parameter determines the
    format of the result string. See QTime::toString() and QDate::toString() for
    the supported specifiers for time and date, respectively.

    Any sequence of characters enclosed in single quotes will be included
    verbatim in the output string (stripped of the quotes), even if it contains
    formatting characters. Two consecutive single quotes ("''") are replaced by
    a single quote in the output. All other characters in the format string are
    included verbatim in the output string.

    Formats without separators (e.g. "ddMM") are supported but must be used with
    care, as the resulting strings aren't always reliably readable (e.g. if "dM"
    produces "212" it could mean either the 2nd of December or the 21st of
    February).

    Example format strings (assumed that the QDateTime is 21 May 2001
    14:13:09.120):

    \table
    \header \li Format       \li Result
    \row \li dd.MM.yyyy      \li 21.05.2001
    \row \li ddd MMMM d yy   \li Tue May 21 01
    \row \li hh:mm:ss.zzz    \li 14:13:09.120
    \row \li hh:mm:ss.z      \li 14:13:09.12
    \row \li h:m:s ap        \li 2:13:9 pm
    \endtable

    If the datetime is invalid, an empty string will be returned.

    \sa fromString(), QDate::toString(), QTime::toString(), QLocale::toString()
*/
QString QDateTime::toString(QStringView format) const
{
    return QLocale::system().toString(*this, format); // QLocale::c() ### Qt6
}

#if QT_STRINGVIEW_LEVEL < 2
QString QDateTime::toString(const QString &format) const
{
    return toString(qToStringViewIgnoringNull(format));
}
#endif

#endif // datestring

static inline void massageAdjustedDateTime(const QDateTimeData &d, QDate *date, QTime *time)
{
    /*
      If we have just adjusted to a day with a DST transition, our given time
      may lie in the transition hour (either missing or duplicated).  For any
      other time, telling mktime (deep in the bowels of localMSecsToEpochMSecs)
      we don't know its DST-ness will produce no adjustment (just a decision as
      to its DST-ness); but for a time in spring's missing hour it'll adjust the
      time while picking a DST-ness.  (Handling of autumn is trickier, as either
      DST-ness is valid, without adjusting the time.  We might want to propagate
      the daylight status in that case, but it's hard to do so without breaking
      (far more common) other cases; and it makes little difference, as the two
      answers do then differ only in DST-ness.)
    */
    auto spec = getSpec(d);
    if (spec == Qt::LocalTime) {
        QDateTimePrivate::DaylightStatus status = QDateTimePrivate::UnknownDaylightTime;
        localMSecsToEpochMSecs(timeToMSecs(*date, *time), &status, date, time);
#if QT_CONFIG(timezone)
    } else if (spec == Qt::TimeZone && d->m_timeZone.isValid()) {
        QDateTimePrivate::zoneMSecsToEpochMSecs(timeToMSecs(*date, *time),
                                                d->m_timeZone,
                                                QDateTimePrivate::UnknownDaylightTime,
                                                date, time);
#endif // timezone
    }
}

/*!
    Returns a QDateTime object containing a datetime \a ndays days
    later than the datetime of this object (or earlier if \a ndays is
    negative).

    If the timeSpec() is Qt::LocalTime and the resulting
    date and time fall in the Standard Time to Daylight-Saving Time transition
    hour then the result will be adjusted accordingly, i.e. if the transition
    is at 2am and the clock goes forward to 3am and the result falls between
    2am and 3am then the result will be adjusted to fall after 3am.

    \sa daysTo(), addMonths(), addYears(), addSecs()
*/

QDateTime QDateTime::addDays(qint64 ndays) const
{
    QDateTime dt(*this);
    QPair<QDate, QTime> p = getDateTime(d);
    QDate &date = p.first;
    QTime &time = p.second;
    date = date.addDays(ndays);
    massageAdjustedDateTime(dt.d, &date, &time);
    setDateTime(dt.d, date, time);
    return dt;
}

/*!
    Returns a QDateTime object containing a datetime \a nmonths months
    later than the datetime of this object (or earlier if \a nmonths
    is negative).

    If the timeSpec() is Qt::LocalTime and the resulting
    date and time fall in the Standard Time to Daylight-Saving Time transition
    hour then the result will be adjusted accordingly, i.e. if the transition
    is at 2am and the clock goes forward to 3am and the result falls between
    2am and 3am then the result will be adjusted to fall after 3am.

    \sa daysTo(), addDays(), addYears(), addSecs()
*/

QDateTime QDateTime::addMonths(int nmonths) const
{
    QDateTime dt(*this);
    QPair<QDate, QTime> p = getDateTime(d);
    QDate &date = p.first;
    QTime &time = p.second;
    date = date.addMonths(nmonths);
    massageAdjustedDateTime(dt.d, &date, &time);
    setDateTime(dt.d, date, time);
    return dt;
}

/*!
    Returns a QDateTime object containing a datetime \a nyears years
    later than the datetime of this object (or earlier if \a nyears is
    negative).

    If the timeSpec() is Qt::LocalTime and the resulting
    date and time fall in the Standard Time to Daylight-Saving Time transition
    hour then the result will be adjusted accordingly, i.e. if the transition
    is at 2am and the clock goes forward to 3am and the result falls between
    2am and 3am then the result will be adjusted to fall after 3am.

    \sa daysTo(), addDays(), addMonths(), addSecs()
*/

QDateTime QDateTime::addYears(int nyears) const
{
    QDateTime dt(*this);
    QPair<QDate, QTime> p = getDateTime(d);
    QDate &date = p.first;
    QTime &time = p.second;
    date = date.addYears(nyears);
    massageAdjustedDateTime(dt.d, &date, &time);
    setDateTime(dt.d, date, time);
    return dt;
}

/*!
    Returns a QDateTime object containing a datetime \a s seconds
    later than the datetime of this object (or earlier if \a s is
    negative).

    If this datetime is invalid, an invalid datetime will be returned.

    \sa addMSecs(), secsTo(), addDays(), addMonths(), addYears()
*/

QDateTime QDateTime::addSecs(qint64 s) const
{
    return addMSecs(s * 1000);
}

/*!
    Returns a QDateTime object containing a datetime \a msecs miliseconds
    later than the datetime of this object (or earlier if \a msecs is
    negative).

    If this datetime is invalid, an invalid datetime will be returned.

    \sa addSecs(), msecsTo(), addDays(), addMonths(), addYears()
*/
QDateTime QDateTime::addMSecs(qint64 msecs) const
{
    if (!isValid())
        return QDateTime();

    QDateTime dt(*this);
    auto spec = getSpec(d);
    if (spec == Qt::LocalTime || spec == Qt::TimeZone) {
        // Convert to real UTC first in case crosses DST transition
        dt.setMSecsSinceEpoch(toMSecsSinceEpoch() + msecs);
    } else {
        // No need to convert, just add on
        if (d.isShort()) {
            // need to check if we need to enlarge first
            msecs += dt.d.data.msecs;
            if (msecsCanBeSmall(msecs)) {
                dt.d.data.msecs = qintptr(msecs);
            } else {
                dt.d.detach();
                dt.d->m_msecs = msecs;
            }
        } else {
            dt.d.detach();
            dt.d->m_msecs += msecs;
        }
    }
    return dt;
}

/*!
    Returns the number of days from this datetime to the \a other
    datetime. The number of days is counted as the number of times
    midnight is reached between this datetime to the \a other
    datetime. This means that a 10 minute difference from 23:55 to
    0:05 the next day counts as one day.

    If the \a other datetime is earlier than this datetime,
    the value returned is negative.

    Example:
    \snippet code/src_corelib_tools_qdatetime.cpp 15

    \sa addDays(), secsTo(), msecsTo()
*/

qint64 QDateTime::daysTo(const QDateTime &other) const
{
    return date().daysTo(other.date());
}

/*!
    Returns the number of seconds from this datetime to the \a other
    datetime. If the \a other datetime is earlier than this datetime,
    the value returned is negative.

    Before performing the comparison, the two datetimes are converted
    to Qt::UTC to ensure that the result is correct if daylight-saving
    (DST) applies to one of the two datetimes but not the other.

    Returns 0 if either datetime is invalid.

    Example:
    \snippet code/src_corelib_tools_qdatetime.cpp 11

    \sa addSecs(), daysTo(), QTime::secsTo()
*/

qint64 QDateTime::secsTo(const QDateTime &other) const
{
    return (msecsTo(other) / 1000);
}

/*!
    Returns the number of milliseconds from this datetime to the \a other
    datetime. If the \a other datetime is earlier than this datetime,
    the value returned is negative.

    Before performing the comparison, the two datetimes are converted
    to Qt::UTC to ensure that the result is correct if daylight-saving
    (DST) applies to one of the two datetimes and but not the other.

    Returns 0 if either datetime is invalid.

    \sa addMSecs(), daysTo(), QTime::msecsTo()
*/

qint64 QDateTime::msecsTo(const QDateTime &other) const
{
    if (!isValid() || !other.isValid())
        return 0;

    return other.toMSecsSinceEpoch() - toMSecsSinceEpoch();
}

/*!
    \fn QDateTime QDateTime::toTimeSpec(Qt::TimeSpec spec) const

    Returns a copy of this datetime converted to the given time
    \a spec.

    If \a spec is Qt::OffsetFromUTC then it is set to Qt::UTC.  To set to a
    spec of Qt::OffsetFromUTC use toOffsetFromUtc().

    If \a spec is Qt::TimeZone then it is set to Qt::LocalTime,
    i.e. the local Time Zone.

    Example:
    \snippet code/src_corelib_tools_qdatetime.cpp 16

    \sa timeSpec(), toTimeZone(), toOffsetFromUtc()
*/

QDateTime QDateTime::toTimeSpec(Qt::TimeSpec spec) const
{
    if (getSpec(d) == spec && (spec == Qt::UTC || spec == Qt::LocalTime))
        return *this;

    if (!isValid()) {
        QDateTime ret = *this;
        ret.setTimeSpec(spec);
        return ret;
    }

    return fromMSecsSinceEpoch(toMSecsSinceEpoch(), spec, 0);
}

/*!
    \since 5.2

    \fn QDateTime QDateTime::toOffsetFromUtc(int offsetSeconds) const

    Returns a copy of this datetime converted to a spec of Qt::OffsetFromUTC
    with the given \a offsetSeconds.

    If the \a offsetSeconds equals 0 then a UTC datetime will be returned

    \sa setOffsetFromUtc(), offsetFromUtc(), toTimeSpec()
*/

QDateTime QDateTime::toOffsetFromUtc(int offsetSeconds) const
{
    if (getSpec(d) == Qt::OffsetFromUTC
            && d->m_offsetFromUtc == offsetSeconds)
        return *this;

    if (!isValid()) {
        QDateTime ret = *this;
        ret.setOffsetFromUtc(offsetSeconds);
        return ret;
    }

    return fromMSecsSinceEpoch(toMSecsSinceEpoch(), Qt::OffsetFromUTC, offsetSeconds);
}

#if QT_CONFIG(timezone)
/*!
    \since 5.2

    Returns a copy of this datetime converted to the given \a timeZone

    \sa timeZone(), toTimeSpec()
*/

QDateTime QDateTime::toTimeZone(const QTimeZone &timeZone) const
{
    if (getSpec(d) == Qt::TimeZone && d->m_timeZone == timeZone)
        return *this;

    if (!isValid()) {
        QDateTime ret = *this;
        ret.setTimeZone(timeZone);
        return ret;
    }

    return fromMSecsSinceEpoch(toMSecsSinceEpoch(), timeZone);
}
#endif // timezone

/*!
    Returns \c true if this datetime is equal to the \a other datetime;
    otherwise returns \c false.

    Since 5.14, all invalid datetimes are equal to one another and differ from
    all other datetimes.

    \sa operator!=()
*/

bool QDateTime::operator==(const QDateTime &other) const
{
    if (!isValid())
        return !other.isValid();
    if (!other.isValid())
        return false;

    if (getSpec(d) == Qt::LocalTime && getStatus(d) == getStatus(other.d))
        return getMSecs(d) == getMSecs(other.d);

    // Convert to UTC and compare
    return toMSecsSinceEpoch() == other.toMSecsSinceEpoch();
}

/*!
    \fn bool QDateTime::operator!=(const QDateTime &other) const

    Returns \c true if this datetime is different from the \a other
    datetime; otherwise returns \c false.

    Two datetimes are different if either the date, the time, or the time zone
    components are different. Since 5.14, any invalid datetime is less than all
    valid datetimes.

    \sa operator==()
*/

/*!
    Returns \c true if this datetime is earlier than the \a other
    datetime; otherwise returns \c false.
*/

bool QDateTime::operator<(const QDateTime &other) const
{
    if (!isValid())
        return other.isValid();
    if (!other.isValid())
        return false;

    if (getSpec(d) == Qt::LocalTime && getStatus(d) == getStatus(other.d))
        return getMSecs(d) < getMSecs(other.d);

    // Convert to UTC and compare
    return toMSecsSinceEpoch() < other.toMSecsSinceEpoch();
}

/*!
    \fn bool QDateTime::operator<=(const QDateTime &other) const

    Returns \c true if this datetime is earlier than or equal to the
    \a other datetime; otherwise returns \c false.
*/

/*!
    \fn bool QDateTime::operator>(const QDateTime &other) const

    Returns \c true if this datetime is later than the \a other datetime;
    otherwise returns \c false.
*/

/*!
    \fn bool QDateTime::operator>=(const QDateTime &other) const

    Returns \c true if this datetime is later than or equal to the
    \a other datetime; otherwise returns \c false.
*/

/*!
    \fn QDateTime QDateTime::currentDateTime()
    Returns the current datetime, as reported by the system clock, in
    the local time zone.

    \sa currentDateTimeUtc(), QDate::currentDate(), QTime::currentTime(), toTimeSpec()
*/

/*!
    \fn QDateTime QDateTime::currentDateTimeUtc()
    \since 4.7
    Returns the current datetime, as reported by the system clock, in
    UTC.

    \sa currentDateTime(), QDate::currentDate(), QTime::currentTime(), toTimeSpec()
*/

/*!
    \fn qint64 QDateTime::currentMSecsSinceEpoch()
    \since 4.7

    Returns the number of milliseconds since 1970-01-01T00:00:00 Universal
    Coordinated Time. This number is like the POSIX time_t variable, but
    expressed in milliseconds instead.

    \sa currentDateTime(), currentDateTimeUtc(), toTime_t(), toTimeSpec()
*/

/*!
    \fn qint64 QDateTime::currentSecsSinceEpoch()
    \since 5.8

    Returns the number of seconds since 1970-01-01T00:00:00 Universal
    Coordinated Time.

    \sa currentMSecsSinceEpoch()
*/

#if defined(Q_OS_WIN)
static inline uint msecsFromDecomposed(int hour, int minute, int sec, int msec = 0)
{
    return MSECS_PER_HOUR * hour + MSECS_PER_MIN * minute + 1000 * sec + msec;
}

QDate QDate::currentDate()
{
    SYSTEMTIME st;
    memset(&st, 0, sizeof(SYSTEMTIME));
    GetLocalTime(&st);
    return QDate(st.wYear, st.wMonth, st.wDay);
}

QTime QTime::currentTime()
{
    QTime ct;
    SYSTEMTIME st;
    memset(&st, 0, sizeof(SYSTEMTIME));
    GetLocalTime(&st);
    ct.setHMS(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
    return ct;
}

QDateTime QDateTime::currentDateTime()
{
    QTime t;
    SYSTEMTIME st;
    memset(&st, 0, sizeof(SYSTEMTIME));
    GetLocalTime(&st);
    QDate d(st.wYear, st.wMonth, st.wDay);
    t.mds = msecsFromDecomposed(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
    return QDateTime(d, t);
}

QDateTime QDateTime::currentDateTimeUtc()
{
    QTime t;
    SYSTEMTIME st;
    memset(&st, 0, sizeof(SYSTEMTIME));
    GetSystemTime(&st);
    QDate d(st.wYear, st.wMonth, st.wDay);
    t.mds = msecsFromDecomposed(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
    return QDateTime(d, t, Qt::UTC);
}

qint64 QDateTime::currentMSecsSinceEpoch() noexcept
{
    SYSTEMTIME st;
    memset(&st, 0, sizeof(SYSTEMTIME));
    GetSystemTime(&st);
    const qint64 daysAfterEpoch = QDate(1970, 1, 1).daysTo(QDate(st.wYear, st.wMonth, st.wDay));

    return msecsFromDecomposed(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds) +
           daysAfterEpoch * Q_INT64_C(86400000);
}

qint64 QDateTime::currentSecsSinceEpoch() noexcept
{
    SYSTEMTIME st;
    memset(&st, 0, sizeof(SYSTEMTIME));
    GetSystemTime(&st);
    const qint64 daysAfterEpoch = QDate(1970, 1, 1).daysTo(QDate(st.wYear, st.wMonth, st.wDay));

    return st.wHour * SECS_PER_HOUR + st.wMinute * SECS_PER_MIN + st.wSecond +
           daysAfterEpoch * Q_INT64_C(86400);
}

#elif defined(Q_OS_UNIX)
QDate QDate::currentDate()
{
    return QDateTime::currentDateTime().date();
}

QTime QTime::currentTime()
{
    return QDateTime::currentDateTime().time();
}

QDateTime QDateTime::currentDateTime()
{
    return fromMSecsSinceEpoch(currentMSecsSinceEpoch(), Qt::LocalTime);
}

QDateTime QDateTime::currentDateTimeUtc()
{
    return fromMSecsSinceEpoch(currentMSecsSinceEpoch(), Qt::UTC);
}

qint64 QDateTime::currentMSecsSinceEpoch() noexcept
{
    // posix compliant system
    // we have milliseconds
    struct timeval tv;
    gettimeofday(&tv, nullptr);
    return qint64(tv.tv_sec) * Q_INT64_C(1000) + tv.tv_usec / 1000;
}

qint64 QDateTime::currentSecsSinceEpoch() noexcept
{
    struct timeval tv;
    gettimeofday(&tv, nullptr);
    return qint64(tv.tv_sec);
}
#else
#error "What system is this?"
#endif

#if QT_DEPRECATED_SINCE(5, 8)
/*!
  \since 4.2
  \deprecated

  Returns a datetime whose date and time are the number of \a seconds
  that have passed since 1970-01-01T00:00:00, Coordinated Universal
  Time (Qt::UTC) and converted to Qt::LocalTime.  On systems that do not
  support time zones, the time will be set as if local time were Qt::UTC.

  \note This function is deprecated. Please use fromSecsSinceEpoch() in new
  code.

  \sa toTime_t(), setTime_t()
*/
QDateTime QDateTime::fromTime_t(uint seconds)
{
    return fromMSecsSinceEpoch((qint64)seconds * 1000, Qt::LocalTime);
}

/*!
  \since 5.2
  \deprecated

  Returns a datetime whose date and time are the number of \a seconds
  that have passed since 1970-01-01T00:00:00, Coordinated Universal
  Time (Qt::UTC) and converted to the given \a spec.

  If the \a spec is not Qt::OffsetFromUTC then the \a offsetSeconds will be
  ignored.  If the \a spec is Qt::OffsetFromUTC and the \a offsetSeconds is 0
  then the spec will be set to Qt::UTC, i.e. an offset of 0 seconds.

  \note This function is deprecated. Please use fromSecsSinceEpoch() in new
  code.

  \sa toTime_t(), setTime_t()
*/
QDateTime QDateTime::fromTime_t(uint seconds, Qt::TimeSpec spec, int offsetSeconds)
{
    return fromMSecsSinceEpoch((qint64)seconds * 1000, spec, offsetSeconds);
}

#if QT_CONFIG(timezone)
/*!
    \since 5.2
    \deprecated

    Returns a datetime whose date and time are the number of \a seconds
    that have passed since 1970-01-01T00:00:00, Coordinated Universal
    Time (Qt::UTC) and with the given \a timeZone.

    \note This function is deprecated. Please use fromSecsSinceEpoch() in new
    code.

    \sa toTime_t(), setTime_t()
*/
QDateTime QDateTime::fromTime_t(uint seconds, const QTimeZone &timeZone)
{
    return fromMSecsSinceEpoch((qint64)seconds * 1000, timeZone);
}
#endif
#endif // QT_DEPRECATED_SINCE(5, 8)

/*!
  \since 4.7

  Returns a datetime whose date and time are the number of milliseconds, \a msecs,
  that have passed since 1970-01-01T00:00:00.000, Coordinated Universal
  Time (Qt::UTC), and converted to Qt::LocalTime.  On systems that do not
  support time zones, the time will be set as if local time were Qt::UTC.

  Note that there are possible values for \a msecs that lie outside the valid
  range of QDateTime, both negative and positive. The behavior of this
  function is undefined for those values.

  \sa toMSecsSinceEpoch(), setMSecsSinceEpoch()
*/
QDateTime QDateTime::fromMSecsSinceEpoch(qint64 msecs)
{
    return fromMSecsSinceEpoch(msecs, Qt::LocalTime);
}

/*!
  \since 5.2

  Returns a datetime whose date and time are the number of milliseconds \a msecs
  that have passed since 1970-01-01T00:00:00.000, Coordinated Universal
  Time (Qt::UTC) and converted to the given \a spec.

  Note that there are possible values for \a msecs that lie outside the valid
  range of QDateTime, both negative and positive. The behavior of this
  function is undefined for those values.

  If the \a spec is not Qt::OffsetFromUTC then the \a offsetSeconds will be
  ignored.  If the \a spec is Qt::OffsetFromUTC and the \a offsetSeconds is 0
  then the spec will be set to Qt::UTC, i.e. an offset of 0 seconds.

  If \a spec is Qt::TimeZone then the spec will be set to Qt::LocalTime,
  i.e. the current system time zone.

  \sa toMSecsSinceEpoch(), setMSecsSinceEpoch()
*/
QDateTime QDateTime::fromMSecsSinceEpoch(qint64 msecs, Qt::TimeSpec spec, int offsetSeconds)
{
    QDateTime dt;
    QT_PREPEND_NAMESPACE(setTimeSpec(dt.d, spec, offsetSeconds));
    dt.setMSecsSinceEpoch(msecs);
    return dt;
}

/*!
  \since 5.8

  Returns a datetime whose date and time are the number of seconds \a secs
  that have passed since 1970-01-01T00:00:00.000, Coordinated Universal
  Time (Qt::UTC) and converted to the given \a spec.

  Note that there are possible values for \a secs that lie outside the valid
  range of QDateTime, both negative and positive. The behavior of this
  function is undefined for those values.

  If the \a spec is not Qt::OffsetFromUTC then the \a offsetSeconds will be
  ignored.  If the \a spec is Qt::OffsetFromUTC and the \a offsetSeconds is 0
  then the spec will be set to Qt::UTC, i.e. an offset of 0 seconds.

  If \a spec is Qt::TimeZone then the spec will be set to Qt::LocalTime,
  i.e. the current system time zone.

  \sa toSecsSinceEpoch(), setSecsSinceEpoch()
*/
QDateTime QDateTime::fromSecsSinceEpoch(qint64 secs, Qt::TimeSpec spec, int offsetSeconds)
{
    return fromMSecsSinceEpoch(secs * 1000, spec, offsetSeconds);
}

#if QT_CONFIG(timezone)
/*!
    \since 5.2

    Returns a datetime whose date and time are the number of milliseconds \a msecs
    that have passed since 1970-01-01T00:00:00.000, Coordinated Universal
    Time (Qt::UTC) and with the given \a timeZone.

    \sa fromSecsSinceEpoch()
*/
QDateTime QDateTime::fromMSecsSinceEpoch(qint64 msecs, const QTimeZone &timeZone)
{
    QDateTime dt;
    dt.setTimeZone(timeZone);
    if (timeZone.isValid())
        dt.setMSecsSinceEpoch(msecs);
    return dt;
}

/*!
    \since 5.8

    Returns a datetime whose date and time are the number of seconds \a secs
    that have passed since 1970-01-01T00:00:00.000, Coordinated Universal
    Time (Qt::UTC) and with the given \a timeZone.

    \sa fromMSecsSinceEpoch()
*/
QDateTime QDateTime::fromSecsSinceEpoch(qint64 secs, const QTimeZone &timeZone)
{
    return fromMSecsSinceEpoch(secs * 1000, timeZone);
}
#endif

#if QT_DEPRECATED_SINCE(5, 2)
/*!
    \since 4.4
    \internal
    \obsolete

    This method was added in 4.4 but never documented as public. It was replaced
    in 5.2 with public method setOffsetFromUtc() for consistency with QTimeZone.

    This method should never be made public.

    \sa setOffsetFromUtc()
 */
void QDateTime::setUtcOffset(int seconds)
{
    setOffsetFromUtc(seconds);
}

/*!
    \since 4.4
    \internal
    \obsolete

    This method was added in 4.4 but never documented as public. It was replaced
    in 5.1 with public method offsetFromUTC() for consistency with QTimeZone.

    This method should never be made public.

    \sa offsetFromUTC()
*/
int QDateTime::utcOffset() const
{
    return offsetFromUtc();
}
#endif // QT_DEPRECATED_SINCE

#if QT_CONFIG(datestring) // depends on, so implies, textdate

/*!
    Returns the QDateTime represented by the \a string, using the
    \a format given, or an invalid datetime if this is not possible.

    Note for Qt::TextDate: It is recommended that you use the
    English short month names (e.g. "Jan"). Although localized month
    names can also be used, they depend on the user's locale settings.

    \sa toString(), QLocale::toDateTime()
*/
QDateTime QDateTime::fromString(const QString &string, Qt::DateFormat format)
{
    if (string.isEmpty())
        return QDateTime();

    switch (format) {
    case Qt::SystemLocaleDate:
    case Qt::SystemLocaleShortDate:
        return QLocale::system().toDateTime(string, QLocale::ShortFormat);
    case Qt::SystemLocaleLongDate:
        return QLocale::system().toDateTime(string, QLocale::LongFormat);
    case Qt::LocaleDate:
    case Qt::DefaultLocaleShortDate:
        return QLocale().toDateTime(string, QLocale::ShortFormat);
    case Qt::DefaultLocaleLongDate:
        return QLocale().toDateTime(string, QLocale::LongFormat);
    case Qt::RFC2822Date: {
        const ParsedRfcDateTime rfc = rfcDateImpl(string);

        if (!rfc.date.isValid() || !rfc.time.isValid())
            return QDateTime();

        QDateTime dateTime(rfc.date, rfc.time, Qt::UTC);
        dateTime.setOffsetFromUtc(rfc.utcOffset);
        return dateTime;
    }
    case Qt::ISODate:
    case Qt::ISODateWithMs: {
        const int size = string.size();
        if (size < 10)
            return QDateTime();

        QDate date = QDate::fromString(string.left(10), Qt::ISODate);
        if (!date.isValid())
            return QDateTime();
        if (size == 10)
            return date.startOfDay();

        Qt::TimeSpec spec = Qt::LocalTime;
        QStringView isoString = QStringView(string).mid(10); // trim "yyyy-MM-dd"

        // Must be left with T (or space) and at least one digit for the hour:
        if (isoString.size() < 2
            || !(isoString.startsWith(QLatin1Char('T'), Qt::CaseInsensitive)
                 // RFC 3339 (section 5.6) allows a space here.  (It actually
                 // allows any separator one considers more readable, merely
                 // giving space as an example - but let's not go wild !)
                 || isoString.startsWith(QLatin1Char(' ')))) {
            return QDateTime();
        }
        isoString = isoString.mid(1); // trim 'T' (or space)

        int offset = 0;
        // Check end of string for Time Zone definition, either Z for UTC or [+-]HH:mm for Offset
        if (isoString.endsWith(QLatin1Char('Z'), Qt::CaseInsensitive)) {
            spec = Qt::UTC;
            isoString.chop(1); // trim 'Z'
        } else {
            // the loop below is faster but functionally equal to:
            // const int signIndex = isoString.indexOf(QRegExp(QStringLiteral("[+-]")));
            int signIndex = isoString.size() - 1;
            Q_ASSERT(signIndex >= 0);
            bool found = false;
            {
                const QChar plus = QLatin1Char('+');
                const QChar minus = QLatin1Char('-');
                do {
                    QChar character(isoString.at(signIndex));
                    found = character == plus || character == minus;
                } while (!found && --signIndex >= 0);
            }

            if (found) {
                bool ok;
                offset = fromOffsetString(isoString.mid(signIndex), &ok);
                if (!ok)
                    return QDateTime();
                isoString = isoString.left(signIndex);
                spec = Qt::OffsetFromUTC;
            }
        }

        // Might be end of day (24:00, including variants), which QTime considers invalid.
        // ISO 8601 (section 4.2.3) says that 24:00 is equivalent to 00:00 the next day.
        bool isMidnight24 = false;
        QTime time = fromIsoTimeString(isoString, format, &isMidnight24);
        if (!time.isValid())
            return QDateTime();
        if (isMidnight24)
            date = date.addDays(1);
        return QDateTime(date, time, spec, offset);
    }
    case Qt::TextDate: {
        QVector<QStringRef> parts = string.splitRef(QLatin1Char(' '), QString::SkipEmptyParts);

        if ((parts.count() < 5) || (parts.count() > 6))
            return QDateTime();

        // Accept "Sun Dec 1 13:02:00 1974" and "Sun 1. Dec 13:02:00 1974"

        // Year and time can be in either order.
        // Guess which by looking for ':' in the time
        int yearPart = 3;
        int timePart = 3;
        if (parts.at(3).contains(QLatin1Char(':')))
            yearPart = 4;
        else if (parts.at(4).contains(QLatin1Char(':')))
            timePart = 4;
        else
            return QDateTime();

        int month = 0;
        int day = 0;
        bool ok = false;

        int year = parts.at(yearPart).toInt(&ok);
        if (!ok || year == 0)
            return QDateTime();

        // Next try month then day
        month = fromShortMonthName(parts.at(1), year);
        if (month)
            day = parts.at(2).toInt(&ok);

        // If failed, try day then month
        if (!ok || !month || !day) {
            month = fromShortMonthName(parts.at(2), year);
            if (month) {
                QStringRef dayStr = parts.at(1);
                if (dayStr.endsWith(QLatin1Char('.'))) {
                    dayStr = dayStr.left(dayStr.size() - 1);
                    day = dayStr.toInt(&ok);
                }
            }
        }

        // If both failed, give up
        if (!ok || !month || !day)
            return QDateTime();

        QDate date(year, month, day);
        if (!date.isValid())
            return QDateTime();

        QVector<QStringRef> timeParts = parts.at(timePart).split(QLatin1Char(':'));
        if (timeParts.count() < 2 || timeParts.count() > 3)
            return QDateTime();

        int hour = timeParts.at(0).toInt(&ok);
        if (!ok)
            return QDateTime();

        int minute = timeParts.at(1).toInt(&ok);
        if (!ok)
            return QDateTime();

        int second = 0;
        int millisecond = 0;
        if (timeParts.count() > 2) {
            const QVector<QStringRef> secondParts = timeParts.at(2).split(QLatin1Char('.'));
            if (secondParts.size() > 2) {
                return QDateTime();
            }

            second = secondParts.first().toInt(&ok);
            if (!ok) {
                return QDateTime();
            }

            if (secondParts.size() > 1) {
                millisecond = secondParts.last().toInt(&ok);
                if (!ok) {
                    return QDateTime();
                }
            }
        }

        QTime time(hour, minute, second, millisecond);
        if (!time.isValid())
            return QDateTime();

        if (parts.count() == 5)
            return QDateTime(date, time, Qt::LocalTime);

        QStringView tz = parts.at(5);
        if (!tz.startsWith(QLatin1String("GMT"), Qt::CaseInsensitive))
            return QDateTime();
        tz = tz.mid(3);
        if (!tz.isEmpty()) {
            int offset = fromOffsetString(tz, &ok);
            if (!ok)
                return QDateTime();
            return QDateTime(date, time, Qt::OffsetFromUTC, offset);
        } else {
            return QDateTime(date, time, Qt::UTC);
        }
    }
    }

    return QDateTime();
}

/*!
    Returns the QDateTime represented by the \a string, using the \a
    format given, or an invalid datetime if the string cannot be parsed.

    Uses the calendar \a cal if supplied, else Gregorian.

    See QDate::fromString() and QTime::fromString() for the expressions
    recognized in the format string to represent parts of the date and time.
    All other input characters will be treated as text. Any sequence of
    characters that are enclosed in single quotes will also be treated as text
    and not be used as an expression.

    \snippet code/src_corelib_tools_qdatetime.cpp 12

    If the format is not satisfied, an invalid QDateTime is returned.
    The expressions that don't have leading zeroes (d, M, h, m, s, z) will be
    greedy. This means that they will use two digits even if this will
    put them outside the range and/or leave too few digits for other
    sections.

    \snippet code/src_corelib_tools_qdatetime.cpp 13

    This could have meant 1 January 00:30.00 but the M will grab
    two digits.

    Incorrectly specified fields of the \a string will cause an invalid
    QDateTime to be returned. For example, consider the following code,
    where the two digit year 12 is read as 1912 (see the table below for all
    field defaults); the resulting datetime is invalid because 23 April 1912
    was a Tuesday, not a Monday:

    \snippet code/src_corelib_tools_qdatetime.cpp 20

    The correct code is:

    \snippet code/src_corelib_tools_qdatetime.cpp 21

    For any field that is not represented in the format, the following
    defaults are used:

    \table
    \header \li Field  \li Default value
    \row    \li Year   \li 1900
    \row    \li Month  \li 1 (January)
    \row    \li Day    \li 1
    \row    \li Hour   \li 0
    \row    \li Minute \li 0
    \row    \li Second \li 0
    \endtable

    For example:

    \snippet code/src_corelib_tools_qdatetime.cpp 14

    \sa toString(), QDate::fromString(), QTime::fromString(),
    QLocale::toDateTime()
*/

QDateTime QDateTime::fromString(const QString &string, const QString &format, QCalendar cal)
{
#if QT_CONFIG(datetimeparser)
    QTime time;
    QDate date;

    QDateTimeParser dt(QVariant::DateTime, QDateTimeParser::FromString, cal);
    // dt.setDefaultLocale(QLocale::c()); ### Qt 6
    if (dt.parseFormat(format) && dt.fromString(string, &date, &time))
        return QDateTime(date, time);
#else
    Q_UNUSED(string);
    Q_UNUSED(format);
    Q_UNUSED(cal);
#endif
    return QDateTime();
}

/*
  \overload
*/

QDateTime QDateTime::fromString(const QString &string, const QString &format)
{
    return fromString(string, format, QCalendar());
}

#endif // datestring
/*!
    \fn QDateTime QDateTime::toLocalTime() const

    Returns a datetime containing the date and time information in
    this datetime, but specified using the Qt::LocalTime definition.

    Example:

    \snippet code/src_corelib_tools_qdatetime.cpp 17

    \sa toTimeSpec()
*/

/*!
    \fn QDateTime QDateTime::toUTC() const

    Returns a datetime containing the date and time information in
    this datetime, but specified using the Qt::UTC definition.

    Example:

    \snippet code/src_corelib_tools_qdatetime.cpp 18

    \sa toTimeSpec()
*/

/*****************************************************************************
  Date/time stream functions
 *****************************************************************************/

#ifndef QT_NO_DATASTREAM
/*!
    \relates QDate

    Writes the \a date to stream \a out.

    \sa {Serializing Qt Data Types}
*/

QDataStream &operator<<(QDataStream &out, const QDate &date)
{
    if (out.version() < QDataStream::Qt_5_0)
        return out << quint32(date.jd);
    else
        return out << qint64(date.jd);
}

/*!
    \relates QDate

    Reads a date from stream \a in into the \a date.

    \sa {Serializing Qt Data Types}
*/

QDataStream &operator>>(QDataStream &in, QDate &date)
{
    if (in.version() < QDataStream::Qt_5_0) {
        quint32 jd;
        in >> jd;
        // Older versions consider 0 an invalid jd.
        date.jd = (jd != 0 ? jd : QDate::nullJd());
    } else {
        qint64 jd;
        in >> jd;
        date.jd = jd;
    }

    return in;
}

/*!
    \relates QTime

    Writes \a time to stream \a out.

    \sa {Serializing Qt Data Types}
*/

QDataStream &operator<<(QDataStream &out, const QTime &time)
{
    if (out.version() >= QDataStream::Qt_4_0) {
        return out << quint32(time.mds);
    } else {
        // Qt3 had no support for reading -1, QTime() was valid and serialized as 0
        return out << quint32(time.isNull() ? 0 : time.mds);
    }
}

/*!
    \relates QTime

    Reads a time from stream \a in into the given \a time.

    \sa {Serializing Qt Data Types}
*/

QDataStream &operator>>(QDataStream &in, QTime &time)
{
    quint32 ds;
    in >> ds;
    if (in.version() >= QDataStream::Qt_4_0) {
        time.mds = int(ds);
    } else {
        // Qt3 would write 0 for a null time
        time.mds = (ds == 0) ? QTime::NullTime : int(ds);
    }
    return in;
}

/*!
    \relates QDateTime

    Writes \a dateTime to the \a out stream.

    \sa {Serializing Qt Data Types}
*/
QDataStream &operator<<(QDataStream &out, const QDateTime &dateTime)
{
    QPair<QDate, QTime> dateAndTime;

    if (out.version() >= QDataStream::Qt_5_2) {

        // In 5.2 we switched to using Qt::TimeSpec and added offset support
        dateAndTime = getDateTime(dateTime.d);
        out << dateAndTime << qint8(dateTime.timeSpec());
        if (dateTime.timeSpec() == Qt::OffsetFromUTC)
            out << qint32(dateTime.offsetFromUtc());
#if QT_CONFIG(timezone)
        else if (dateTime.timeSpec() == Qt::TimeZone)
            out << dateTime.timeZone();
#endif // timezone

    } else if (out.version() == QDataStream::Qt_5_0) {

        // In Qt 5.0 we incorrectly serialised all datetimes as UTC.
        // This approach is wrong and should not be used again; it breaks
        // the guarantee that a deserialised local datetime is the same time
        // of day, regardless of which timezone it was serialised in.
        dateAndTime = getDateTime((dateTime.isValid() ? dateTime.toUTC() : dateTime).d);
        out << dateAndTime << qint8(dateTime.timeSpec());

    } else if (out.version() >= QDataStream::Qt_4_0) {

        // From 4.0 to 5.1 (except 5.0) we used QDateTimePrivate::Spec
        dateAndTime = getDateTime(dateTime.d);
        out << dateAndTime;
        switch (dateTime.timeSpec()) {
        case Qt::UTC:
            out << (qint8)QDateTimePrivate::UTC;
            break;
        case Qt::OffsetFromUTC:
            out << (qint8)QDateTimePrivate::OffsetFromUTC;
            break;
        case Qt::TimeZone:
            out << (qint8)QDateTimePrivate::TimeZone;
            break;
        case Qt::LocalTime:
            out << (qint8)QDateTimePrivate::LocalUnknown;
            break;
        }

    } else { // version < QDataStream::Qt_4_0

        // Before 4.0 there was no TimeSpec, only Qt::LocalTime was supported
        dateAndTime = getDateTime(dateTime.d);
        out << dateAndTime;

    }

    return out;
}

/*!
    \relates QDateTime

    Reads a datetime from the stream \a in into \a dateTime.

    \sa {Serializing Qt Data Types}
*/

QDataStream &operator>>(QDataStream &in, QDateTime &dateTime)
{
    QDate dt;
    QTime tm;
    qint8 ts = 0;
    Qt::TimeSpec spec = Qt::LocalTime;
    qint32 offset = 0;
#if QT_CONFIG(timezone)
    QTimeZone tz;
#endif // timezone

    if (in.version() >= QDataStream::Qt_5_2) {

        // In 5.2 we switched to using Qt::TimeSpec and added offset support
        in >> dt >> tm >> ts;
        spec = static_cast<Qt::TimeSpec>(ts);
        if (spec == Qt::OffsetFromUTC) {
            in >> offset;
            dateTime = QDateTime(dt, tm, spec, offset);
#if QT_CONFIG(timezone)
        } else if (spec == Qt::TimeZone) {
            in >> tz;
            dateTime = QDateTime(dt, tm, tz);
#endif // timezone
        } else {
            dateTime = QDateTime(dt, tm, spec);
        }

    } else if (in.version() == QDataStream::Qt_5_0) {

        // In Qt 5.0 we incorrectly serialised all datetimes as UTC
        in >> dt >> tm >> ts;
        spec = static_cast<Qt::TimeSpec>(ts);
        dateTime = QDateTime(dt, tm, Qt::UTC);
        dateTime = dateTime.toTimeSpec(spec);

    } else if (in.version() >= QDataStream::Qt_4_0) {

        // From 4.0 to 5.1 (except 5.0) we used QDateTimePrivate::Spec
        in >> dt >> tm >> ts;
        switch ((QDateTimePrivate::Spec)ts) {
        case QDateTimePrivate::UTC:
            spec = Qt::UTC;
            break;
        case QDateTimePrivate::OffsetFromUTC:
            spec = Qt::OffsetFromUTC;
            break;
        case QDateTimePrivate::TimeZone:
            spec = Qt::TimeZone;
#if QT_CONFIG(timezone)
            // FIXME: need to use a different constructor !
#endif
            break;
        case QDateTimePrivate::LocalUnknown:
        case QDateTimePrivate::LocalStandard:
        case QDateTimePrivate::LocalDST:
            spec = Qt::LocalTime;
            break;
        }
        dateTime = QDateTime(dt, tm, spec, offset);

    } else { // version < QDataStream::Qt_4_0

        // Before 4.0 there was no TimeSpec, only Qt::LocalTime was supported
        in >> dt >> tm;
        dateTime = QDateTime(dt, tm, spec, offset);

    }

    return in;
}
#endif // QT_NO_DATASTREAM

/*****************************************************************************
  Date / Time Debug Streams
*****************************************************************************/

#if !defined(QT_NO_DEBUG_STREAM) && QT_CONFIG(datestring)
QDebug operator<<(QDebug dbg, const QDate &date)
{
    QDebugStateSaver saver(dbg);
    dbg.nospace() << "QDate(";
    if (date.isValid())
        dbg.nospace() << date.toString(Qt::ISODate);
    else
        dbg.nospace() << "Invalid";
    dbg.nospace() << ')';
    return dbg;
}

QDebug operator<<(QDebug dbg, const QTime &time)
{
    QDebugStateSaver saver(dbg);
    dbg.nospace() << "QTime(";
    if (time.isValid())
        dbg.nospace() << time.toString(u"HH:mm:ss.zzz");
    else
        dbg.nospace() << "Invalid";
    dbg.nospace() << ')';
    return dbg;
}

QDebug operator<<(QDebug dbg, const QDateTime &date)
{
    QDebugStateSaver saver(dbg);
    dbg.nospace() << "QDateTime(";
    if (date.isValid()) {
        const Qt::TimeSpec ts = date.timeSpec();
        dbg.noquote() << date.toString(u"yyyy-MM-dd HH:mm:ss.zzz t")
                      << ' ' << ts;
        switch (ts) {
        case Qt::UTC:
            break;
        case Qt::OffsetFromUTC:
            dbg.space() << date.offsetFromUtc() << 's';
            break;
        case Qt::TimeZone:
#if QT_CONFIG(timezone)
            dbg.space() << date.timeZone().id();
#endif // timezone
            break;
        case Qt::LocalTime:
            break;
        }
    } else {
        dbg.nospace() << "Invalid";
    }
    return dbg.nospace() << ')';
}
#endif // debug_stream && datestring

/*! \fn uint qHash(const QDateTime &key, uint seed = 0)
    \relates QHash
    \since 5.0

    Returns the hash value for the \a key, using \a seed to seed the calculation.
*/
uint qHash(const QDateTime &key, uint seed)
{
    // Use to toMSecsSinceEpoch instead of individual qHash functions for
    // QDate/QTime/spec/offset because QDateTime::operator== converts both arguments
    // to the same timezone. If we don't, qHash would return different hashes for
    // two QDateTimes that are equivalent once converted to the same timezone.
    return key.isValid() ? qHash(key.toMSecsSinceEpoch(), seed) : seed;
}

/*! \fn uint qHash(const QDate &key, uint seed = 0)
    \relates QHash
    \since 5.0

    Returns the hash value for the \a key, using \a seed to seed the calculation.
*/
uint qHash(const QDate &key, uint seed) noexcept
{
    return qHash(key.toJulianDay(), seed);
}

/*! \fn uint qHash(const QTime &key, uint seed = 0)
    \relates QHash
    \since 5.0

    Returns the hash value for the \a key, using \a seed to seed the calculation.
*/
uint qHash(const QTime &key, uint seed) noexcept
{
    return qHash(key.msecsSinceStartOfDay(), seed);
}

QT_END_NAMESPACE