CarbonInterval.php
103.6 KB
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
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon;
use Carbon\Exceptions\BadFluentConstructorException;
use Carbon\Exceptions\BadFluentSetterException;
use Carbon\Exceptions\InvalidCastException;
use Carbon\Exceptions\InvalidIntervalException;
use Carbon\Exceptions\OutOfRangeException;
use Carbon\Exceptions\ParseErrorException;
use Carbon\Exceptions\UnitNotConfiguredException;
use Carbon\Exceptions\UnknownGetterException;
use Carbon\Exceptions\UnknownSetterException;
use Carbon\Exceptions\UnknownUnitException;
use Carbon\Traits\IntervalRounding;
use Carbon\Traits\IntervalStep;
use Carbon\Traits\MagicParameter;
use Carbon\Traits\Mixin;
use Carbon\Traits\Options;
use Carbon\Traits\ToStringFormat;
use Closure;
use DateInterval;
use DateMalformedIntervalStringException;
use DateTimeInterface;
use DateTimeZone;
use Exception;
use InvalidArgumentException;
use ReflectionException;
use ReturnTypeWillChange;
use RuntimeException;
use Throwable;
/**
* A simple API extension for DateInterval.
* The implementation provides helpers to handle weeks but only days are saved.
* Weeks are calculated based on the total days of the current instance.
*
* @property int $years Total years of the current interval.
* @property int $months Total months of the current interval.
* @property int $weeks Total weeks of the current interval calculated from the days.
* @property int $dayz Total days of the current interval (weeks * 7 + days).
* @property int $hours Total hours of the current interval.
* @property int $minutes Total minutes of the current interval.
* @property int $seconds Total seconds of the current interval.
* @property int $microseconds Total microseconds of the current interval.
* @property int $milliseconds Total milliseconds of the current interval.
* @property int $microExcludeMilli Remaining microseconds without the milliseconds.
* @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7).
* @property int $daysExcludeWeeks alias of dayzExcludeWeeks
* @property-read float $totalYears Number of years equivalent to the interval.
* @property-read float $totalMonths Number of months equivalent to the interval.
* @property-read float $totalWeeks Number of weeks equivalent to the interval.
* @property-read float $totalDays Number of days equivalent to the interval.
* @property-read float $totalDayz Alias for totalDays.
* @property-read float $totalHours Number of hours equivalent to the interval.
* @property-read float $totalMinutes Number of minutes equivalent to the interval.
* @property-read float $totalSeconds Number of seconds equivalent to the interval.
* @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval.
* @property-read float $totalMicroseconds Number of microseconds equivalent to the interval.
* @property-read string $locale locale of the current instance
*
* @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance.
* @method static CarbonInterval year($years = 1) Alias for years()
* @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance.
* @method static CarbonInterval month($months = 1) Alias for months()
* @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance.
* @method static CarbonInterval week($weeks = 1) Alias for weeks()
* @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance.
* @method static CarbonInterval dayz($days = 1) Alias for days()
* @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance.
* @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks()
* @method static CarbonInterval day($days = 1) Alias for days()
* @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance.
* @method static CarbonInterval hour($hours = 1) Alias for hours()
* @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance.
* @method static CarbonInterval minute($minutes = 1) Alias for minutes()
* @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance.
* @method static CarbonInterval second($seconds = 1) Alias for seconds()
* @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance.
* @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds()
* @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance.
* @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds()
* @method $this addYears(int $years) Add given number of years to the current interval
* @method $this subYears(int $years) Subtract given number of years to the current interval
* @method $this addMonths(int $months) Add given number of months to the current interval
* @method $this subMonths(int $months) Subtract given number of months to the current interval
* @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval
* @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval
* @method $this addDays(int|float $days) Add given number of days to the current interval
* @method $this subDays(int|float $days) Subtract given number of days to the current interval
* @method $this addHours(int|float $hours) Add given number of hours to the current interval
* @method $this subHours(int|float $hours) Subtract given number of hours to the current interval
* @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval
* @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval
* @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval
* @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval
* @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval
* @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval
* @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval
* @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval
* @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function.
* @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function.
* @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision.
* @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision.
* @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision.
* @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision.
* @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function.
* @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function.
* @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision.
* @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision.
* @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision.
* @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision.
* @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
* @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
* @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision.
* @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision.
* @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision.
* @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision.
* @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
* @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
* @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision.
* @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision.
* @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision.
* @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision.
* @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function.
* @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function.
* @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision.
* @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision.
* @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision.
* @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision.
* @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function.
* @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function.
* @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision.
* @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision.
* @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision.
* @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision.
* @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function.
* @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function.
* @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision.
* @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision.
* @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision.
* @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision.
* @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function.
* @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function.
* @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision.
* @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision.
* @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision.
* @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision.
* @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function.
* @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function.
* @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision.
* @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision.
* @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision.
* @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision.
* @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function.
* @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function.
* @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision.
* @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision.
* @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision.
* @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision.
* @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function.
* @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function.
* @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision.
* @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision.
* @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision.
* @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision.
* @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function.
* @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function.
* @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision.
* @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision.
* @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision.
* @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision.
* @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function.
* @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function.
* @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision.
* @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision.
* @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision.
* @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision.
*/
class CarbonInterval extends DateInterval implements CarbonConverterInterface
{
use IntervalRounding;
use IntervalStep;
use MagicParameter;
use Mixin {
Mixin::mixin as baseMixin;
}
use Options;
use ToStringFormat;
/**
* Interval spec period designators
*/
public const PERIOD_PREFIX = 'P';
public const PERIOD_YEARS = 'Y';
public const PERIOD_MONTHS = 'M';
public const PERIOD_DAYS = 'D';
public const PERIOD_TIME_PREFIX = 'T';
public const PERIOD_HOURS = 'H';
public const PERIOD_MINUTES = 'M';
public const PERIOD_SECONDS = 'S';
/**
* A translator to ... er ... translate stuff
*
* @var \Symfony\Component\Translation\TranslatorInterface
*/
protected static $translator;
/**
* @var array|null
*/
protected static $cascadeFactors;
/**
* @var array
*/
protected static $formats = [
'y' => 'y',
'Y' => 'y',
'o' => 'y',
'm' => 'm',
'n' => 'm',
'W' => 'weeks',
'd' => 'd',
'j' => 'd',
'z' => 'd',
'h' => 'h',
'g' => 'h',
'H' => 'h',
'G' => 'h',
'i' => 'i',
's' => 's',
'u' => 'micro',
'v' => 'milli',
];
/**
* @var array|null
*/
private static $flipCascadeFactors;
/**
* @var bool
*/
private static $floatSettersEnabled = false;
/**
* The registered macros.
*
* @var array
*/
protected static $macros = [];
/**
* Timezone handler for settings() method.
*
* @var mixed
*/
protected $tzName;
/**
* Set the instance's timezone from a string or object.
*
* @param \DateTimeZone|string $tzName
*
* @return static
*/
public function setTimezone($tzName)
{
$this->tzName = $tzName;
return $this;
}
/**
* @internal
*
* Set the instance's timezone from a string or object and add/subtract the offset difference.
*
* @param \DateTimeZone|string $tzName
*
* @return static
*/
public function shiftTimezone($tzName)
{
$this->tzName = $tzName;
return $this;
}
/**
* Mapping of units and factors for cascading.
*
* Should only be modified by changing the factors or referenced constants.
*
* @return array
*/
public static function getCascadeFactors()
{
return static::$cascadeFactors ?: static::getDefaultCascadeFactors();
}
protected static function getDefaultCascadeFactors(): array
{
return [
'milliseconds' => [Carbon::MICROSECONDS_PER_MILLISECOND, 'microseconds'],
'seconds' => [Carbon::MILLISECONDS_PER_SECOND, 'milliseconds'],
'minutes' => [Carbon::SECONDS_PER_MINUTE, 'seconds'],
'hours' => [Carbon::MINUTES_PER_HOUR, 'minutes'],
'dayz' => [Carbon::HOURS_PER_DAY, 'hours'],
'weeks' => [Carbon::DAYS_PER_WEEK, 'dayz'],
'months' => [Carbon::WEEKS_PER_MONTH, 'weeks'],
'years' => [Carbon::MONTHS_PER_YEAR, 'months'],
];
}
private static function standardizeUnit($unit)
{
$unit = rtrim($unit, 'sz').'s';
return $unit === 'days' ? 'dayz' : $unit;
}
private static function getFlipCascadeFactors()
{
if (!self::$flipCascadeFactors) {
self::$flipCascadeFactors = [];
foreach (static::getCascadeFactors() as $to => [$factor, $from]) {
self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor];
}
}
return self::$flipCascadeFactors;
}
/**
* Set default cascading factors for ->cascade() method.
*
* @param array $cascadeFactors
*/
public static function setCascadeFactors(array $cascadeFactors)
{
self::$flipCascadeFactors = null;
static::$cascadeFactors = $cascadeFactors;
}
/**
* This option allow you to opt-in for the Carbon 3 behavior where float
* values will no longer be cast to integer (so truncated).
*
* ⚠️ This settings will be applied globally, which mean your whole application
* code including the third-party dependencies that also may use Carbon will
* adopt the new behavior.
*/
public static function enableFloatSetters(bool $floatSettersEnabled = true): void
{
self::$floatSettersEnabled = $floatSettersEnabled;
}
///////////////////////////////////////////////////////////////////
//////////////////////////// CONSTRUCTORS /////////////////////////
///////////////////////////////////////////////////////////////////
/**
* Create a new CarbonInterval instance.
*
* @param Closure|DateInterval|string|int|null $years
* @param int|float|null $months
* @param int|float|null $weeks
* @param int|float|null $days
* @param int|float|null $hours
* @param int|float|null $minutes
* @param int|float|null $seconds
* @param int|float|null $microseconds
*
* @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval.
*/
public function __construct($years = 1, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null)
{
if ($years instanceof Closure) {
$this->step = $years;
$years = null;
}
if ($years instanceof DateInterval) {
parent::__construct(static::getDateIntervalSpec($years));
$this->f = $years->f;
self::copyNegativeUnits($years, $this);
return;
}
$spec = $years;
$isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec));
if (!$isStringSpec || (float) $years) {
$spec = static::PERIOD_PREFIX;
$spec .= $years > 0 ? $years.static::PERIOD_YEARS : '';
$spec .= $months > 0 ? $months.static::PERIOD_MONTHS : '';
$specDays = 0;
$specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0;
$specDays += $days > 0 ? $days : 0;
$spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : '';
if ($hours > 0 || $minutes > 0 || $seconds > 0) {
$spec .= static::PERIOD_TIME_PREFIX;
$spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : '';
$spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : '';
$spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : '';
}
if ($spec === static::PERIOD_PREFIX) {
// Allow the zero interval.
$spec .= '0'.static::PERIOD_YEARS;
}
}
try {
parent::__construct($spec);
} catch (Throwable $exception) {
try {
parent::__construct('PT0S');
if ($isStringSpec) {
if (!preg_match('/^P
(?:(?<year>[+-]?\d*(?:\.\d+)?)Y)?
(?:(?<month>[+-]?\d*(?:\.\d+)?)M)?
(?:(?<week>[+-]?\d*(?:\.\d+)?)W)?
(?:(?<day>[+-]?\d*(?:\.\d+)?)D)?
(?:T
(?:(?<hour>[+-]?\d*(?:\.\d+)?)H)?
(?:(?<minute>[+-]?\d*(?:\.\d+)?)M)?
(?:(?<second>[+-]?\d*(?:\.\d+)?)S)?
)?
$/x', $spec, $match)) {
throw new InvalidArgumentException("Invalid duration: $spec");
}
$years = (float) ($match['year'] ?? 0);
$this->assertSafeForInteger('year', $years);
$months = (float) ($match['month'] ?? 0);
$this->assertSafeForInteger('month', $months);
$weeks = (float) ($match['week'] ?? 0);
$this->assertSafeForInteger('week', $weeks);
$days = (float) ($match['day'] ?? 0);
$this->assertSafeForInteger('day', $days);
$hours = (float) ($match['hour'] ?? 0);
$this->assertSafeForInteger('hour', $hours);
$minutes = (float) ($match['minute'] ?? 0);
$this->assertSafeForInteger('minute', $minutes);
$seconds = (float) ($match['second'] ?? 0);
$this->assertSafeForInteger('second', $seconds);
}
$totalDays = (($weeks * static::getDaysPerWeek()) + $days);
$this->assertSafeForInteger('days total (including weeks)', $totalDays);
$this->y = (int) $years;
$this->m = (int) $months;
$this->d = (int) $totalDays;
$this->h = (int) $hours;
$this->i = (int) $minutes;
$this->s = (int) $seconds;
if (
((float) $this->y) !== $years ||
((float) $this->m) !== $months ||
((float) $this->d) !== $totalDays ||
((float) $this->h) !== $hours ||
((float) $this->i) !== $minutes ||
((float) $this->s) !== $seconds
) {
$this->add(static::fromString(
($years - $this->y).' years '.
($months - $this->m).' months '.
($totalDays - $this->d).' days '.
($hours - $this->h).' hours '.
($minutes - $this->i).' minutes '.
($seconds - $this->s).' seconds '
));
}
} catch (Throwable $secondException) {
throw $secondException instanceof OutOfRangeException ? $secondException : $exception;
}
}
if ($microseconds !== null) {
$this->f = $microseconds / Carbon::MICROSECONDS_PER_SECOND;
}
}
/**
* Returns the factor for a given source-to-target couple.
*
* @param string $source
* @param string $target
*
* @return int|float|null
*/
public static function getFactor($source, $target)
{
$source = self::standardizeUnit($source);
$target = self::standardizeUnit($target);
$factors = self::getFlipCascadeFactors();
if (isset($factors[$source])) {
[$to, $factor] = $factors[$source];
if ($to === $target) {
return $factor;
}
return $factor * static::getFactor($to, $target);
}
return null;
}
/**
* Returns the factor for a given source-to-target couple if set,
* else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK.
*
* @param string $source
* @param string $target
*
* @return int|float|null
*/
public static function getFactorWithDefault($source, $target)
{
$factor = self::getFactor($source, $target);
if ($factor) {
return $factor;
}
static $defaults = [
'month' => ['year' => Carbon::MONTHS_PER_YEAR],
'week' => ['month' => Carbon::WEEKS_PER_MONTH],
'day' => ['week' => Carbon::DAYS_PER_WEEK],
'hour' => ['day' => Carbon::HOURS_PER_DAY],
'minute' => ['hour' => Carbon::MINUTES_PER_HOUR],
'second' => ['minute' => Carbon::SECONDS_PER_MINUTE],
'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND],
'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND],
];
return $defaults[$source][$target] ?? null;
}
/**
* Returns current config for days per week.
*
* @return int|float
*/
public static function getDaysPerWeek()
{
return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK;
}
/**
* Returns current config for hours per day.
*
* @return int|float
*/
public static function getHoursPerDay()
{
return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY;
}
/**
* Returns current config for minutes per hour.
*
* @return int|float
*/
public static function getMinutesPerHour()
{
return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR;
}
/**
* Returns current config for seconds per minute.
*
* @return int|float
*/
public static function getSecondsPerMinute()
{
return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE;
}
/**
* Returns current config for microseconds per second.
*
* @return int|float
*/
public static function getMillisecondsPerSecond()
{
return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND;
}
/**
* Returns current config for microseconds per second.
*
* @return int|float
*/
public static function getMicrosecondsPerMillisecond()
{
return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND;
}
/**
* Create a new CarbonInterval instance from specific values.
* This is an alias for the constructor that allows better fluent
* syntax as it allows you to do CarbonInterval::create(1)->fn() rather than
* (new CarbonInterval(1))->fn().
*
* @param int $years
* @param int $months
* @param int $weeks
* @param int $days
* @param int $hours
* @param int $minutes
* @param int $seconds
* @param int $microseconds
*
* @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval.
*
* @return static
*/
public static function create($years = 1, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null)
{
return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds);
}
/**
* Parse a string into a new CarbonInterval object according to the specified format.
*
* @example
* ```
* echo Carboninterval::createFromFormat('H:i', '1:30');
* ```
*
* @param string $format Format of the $interval input string
* @param string|null $interval Input string to convert into an interval
*
* @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval.
*
* @return static
*/
public static function createFromFormat(string $format, ?string $interval)
{
$instance = new static(0);
$length = mb_strlen($format);
if (preg_match('/s([,.])([uv])$/', $format, $match)) {
$interval = explode($match[1], $interval);
$index = \count($interval) - 1;
$interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0');
$interval = implode($match[1], $interval);
}
$interval = $interval ?? '';
for ($index = 0; $index < $length; $index++) {
$expected = mb_substr($format, $index, 1);
$nextCharacter = mb_substr($interval, 0, 1);
$unit = static::$formats[$expected] ?? null;
if ($unit) {
if (!preg_match('/^-?\d+/', $interval, $match)) {
throw new ParseErrorException('number', $nextCharacter);
}
$interval = mb_substr($interval, mb_strlen($match[0]));
$instance->$unit += (int) ($match[0]);
continue;
}
if ($nextCharacter !== $expected) {
throw new ParseErrorException(
"'$expected'",
$nextCharacter,
'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n".
'See https://php.net/manual/en/function.date.php for their meaning'
);
}
$interval = mb_substr($interval, 1);
}
if ($interval !== '') {
throw new ParseErrorException(
'end of string',
$interval
);
}
return $instance;
}
/**
* Get a copy of the instance.
*
* @return static
*/
public function copy()
{
$date = new static(0);
$date->copyProperties($this);
$date->step = $this->step;
return $date;
}
/**
* Get a copy of the instance.
*
* @return static
*/
public function clone()
{
return $this->copy();
}
/**
* Provide static helpers to create instances. Allows CarbonInterval::years(3).
*
* Note: This is done using the magic method to allow static and instance methods to
* have the same names.
*
* @param string $method magic method name called
* @param array $parameters parameters list
*
* @return static|null
*/
public static function __callStatic($method, $parameters)
{
try {
$interval = new static(0);
$localStrictModeEnabled = $interval->localStrictModeEnabled;
$interval->localStrictModeEnabled = true;
$result = static::hasMacro($method)
? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) {
return $interval->callMacro($method, $parameters);
})
: $interval->$method(...$parameters);
$interval->localStrictModeEnabled = $localStrictModeEnabled;
return $result;
} catch (BadFluentSetterException $exception) {
if (Carbon::isStrictModeEnabled()) {
throw new BadFluentConstructorException($method, 0, $exception);
}
return null;
}
}
/**
* Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance.
*
* @param array $dump data as exported by var_export()
*
* @return static
*/
#[ReturnTypeWillChange]
public static function __set_state($dump)
{
/** @noinspection PhpVoidFunctionResultUsedInspection */
/** @var DateInterval $dateInterval */
$dateInterval = parent::__set_state($dump);
return static::instance($dateInterval);
}
/**
* Return the current context from inside a macro callee or a new one if static.
*
* @return static
*/
protected static function this()
{
return end(static::$macroContextStack) ?: new static(0);
}
/**
* Creates a CarbonInterval from string.
*
* Format:
*
* Suffix | Unit | Example | DateInterval expression
* -------|---------|---------|------------------------
* y | years | 1y | P1Y
* mo | months | 3mo | P3M
* w | weeks | 2w | P2W
* d | days | 28d | P28D
* h | hours | 4h | PT4H
* m | minutes | 12m | PT12M
* s | seconds | 59s | PT59S
*
* e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds.
*
* Special cases:
* - An empty string will return a zero interval
* - Fractions are allowed for weeks, days, hours and minutes and will be converted
* and rounded to the next smaller value (caution: 0.5w = 4d)
*
* @param string $intervalDefinition
*
* @return static
*/
public static function fromString($intervalDefinition)
{
if (empty($intervalDefinition)) {
return new static(0);
}
$years = 0;
$months = 0;
$weeks = 0;
$days = 0;
$hours = 0;
$minutes = 0;
$seconds = 0;
$milliseconds = 0;
$microseconds = 0;
$pattern = '/(\d+(?:\.\d+)?)\h*([^\d\h]*)/i';
preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER);
while ([$part, $value, $unit] = array_shift($parts)) {
$intValue = (int) $value;
$fraction = (float) $value - $intValue;
// Fix calculation precision
switch (round($fraction, 6)) {
case 1:
$fraction = 0;
$intValue++;
break;
case 0:
$fraction = 0;
break;
}
switch ($unit === 'µs' ? 'µs' : strtolower($unit)) {
case 'millennia':
case 'millennium':
$years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM;
break;
case 'century':
case 'centuries':
$years += $intValue * CarbonInterface::YEARS_PER_CENTURY;
break;
case 'decade':
case 'decades':
$years += $intValue * CarbonInterface::YEARS_PER_DECADE;
break;
case 'year':
case 'years':
case 'y':
case 'yr':
case 'yrs':
$years += $intValue;
break;
case 'quarter':
case 'quarters':
$months += $intValue * CarbonInterface::MONTHS_PER_QUARTER;
break;
case 'month':
case 'months':
case 'mo':
case 'mos':
$months += $intValue;
break;
case 'week':
case 'weeks':
case 'w':
$weeks += $intValue;
if ($fraction) {
$parts[] = [null, $fraction * static::getDaysPerWeek(), 'd'];
}
break;
case 'day':
case 'days':
case 'd':
$days += $intValue;
if ($fraction) {
$parts[] = [null, $fraction * static::getHoursPerDay(), 'h'];
}
break;
case 'hour':
case 'hours':
case 'h':
$hours += $intValue;
if ($fraction) {
$parts[] = [null, $fraction * static::getMinutesPerHour(), 'm'];
}
break;
case 'minute':
case 'minutes':
case 'm':
$minutes += $intValue;
if ($fraction) {
$parts[] = [null, $fraction * static::getSecondsPerMinute(), 's'];
}
break;
case 'second':
case 'seconds':
case 's':
$seconds += $intValue;
if ($fraction) {
$parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms'];
}
break;
case 'millisecond':
case 'milliseconds':
case 'milli':
case 'ms':
$milliseconds += $intValue;
if ($fraction) {
$microseconds += round($fraction * static::getMicrosecondsPerMillisecond());
}
break;
case 'microsecond':
case 'microseconds':
case 'micro':
case 'µs':
$microseconds += $intValue;
break;
default:
throw new InvalidIntervalException(
sprintf('Invalid part %s in definition %s', $part, $intervalDefinition)
);
}
}
return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds);
}
/**
* Creates a CarbonInterval from string using a different locale.
*
* @param string $interval interval string in the given language (may also contain English).
* @param string|null $locale if locale is null or not specified, current global locale will be used instead.
*
* @return static
*/
public static function parseFromLocale($interval, $locale = null)
{
return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), 'en'));
}
private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = [])
{
$mainClass = DateInterval::class;
if (!is_a($className, $mainClass, true)) {
throw new InvalidCastException("$className is not a sub-class of $mainClass.");
}
$microseconds = $interval->f;
$instance = new $className(static::getDateIntervalSpec($interval, false, $skip));
if ($microseconds) {
$instance->f = $microseconds;
}
if ($interval instanceof self && is_a($className, self::class, true)) {
self::copyStep($interval, $instance);
}
self::copyNegativeUnits($interval, $instance);
return $instance;
}
private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void
{
$to->invert = $from->invert;
foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) {
if ($from->$unit < 0) {
$to->$unit *= -1;
}
}
}
private static function copyStep(self $from, self $to): void
{
$to->setStep($from->getStep());
}
/**
* Cast the current instance into the given class.
*
* @param string $className The $className::instance() method will be called to cast the current object.
*
* @return DateInterval
*/
public function cast(string $className)
{
return self::castIntervalToClass($this, $className);
}
/**
* Create a CarbonInterval instance from a DateInterval one. Can not instance
* DateInterval objects created from DateTime::diff() as you can't externally
* set the $days field.
*
* @param DateInterval $interval
* @param bool $skipCopy set to true to return the passed object
* (without copying it) if it's already of the
* current class
*
* @return static
*/
public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false)
{
if ($skipCopy && $interval instanceof static) {
return $interval;
}
return self::castIntervalToClass($interval, static::class, $skip);
}
/**
* Make a CarbonInterval instance from given variable if possible.
*
* Always return a new instance. Parse only strings and only these likely to be intervals (skip dates
* and recurrences). Throw an exception for invalid format, but otherwise return null.
*
* @param mixed|int|DateInterval|string|Closure|null $interval interval or number of the given $unit
* @param string|null $unit if specified, $interval must be an integer
* @param bool $skipCopy set to true to return the passed object
* (without copying it) if it's already of the
* current class
*
* @return static|null
*/
public static function make($interval, $unit = null, bool $skipCopy = false)
{
if ($unit) {
$interval = "$interval ".Carbon::pluralUnit($unit);
}
if ($interval instanceof DateInterval) {
return static::instance($interval, [], $skipCopy);
}
if ($interval instanceof Closure) {
return new static($interval);
}
if (!\is_string($interval)) {
return null;
}
return static::makeFromString($interval);
}
protected static function makeFromString(string $interval)
{
$interval = preg_replace('/\s+/', ' ', trim($interval));
if (preg_match('/^P[T\d]/', $interval)) {
return new static($interval);
}
if (preg_match('/^(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) {
return static::fromString($interval);
}
// @codeCoverageIgnoreStart
try {
/** @var static $interval */
$interval = static::createFromDateString($interval);
} catch (DateMalformedIntervalStringException $e) {
return null;
}
// @codeCoverageIgnoreEnd
return !$interval || $interval->isEmpty() ? null : $interval;
}
protected function resolveInterval($interval)
{
if (!($interval instanceof self)) {
return self::make($interval);
}
return $interval;
}
/**
* Sets up a DateInterval from the relative parts of the string.
*
* @param string $time
*
* @return static
*
* @link https://php.net/manual/en/dateinterval.createfromdatestring.php
*/
#[ReturnTypeWillChange]
public static function createFromDateString($time)
{
$interval = @parent::createFromDateString(strtr($time, [
',' => ' ',
' and ' => ' ',
]));
if ($interval instanceof DateInterval) {
$interval = static::instance($interval);
}
return $interval;
}
///////////////////////////////////////////////////////////////////
///////////////////////// GETTERS AND SETTERS /////////////////////
///////////////////////////////////////////////////////////////////
/**
* Get a part of the CarbonInterval object.
*
* @param string $name
*
* @throws UnknownGetterException
*
* @return int|float|string
*/
public function get($name)
{
if (str_starts_with($name, 'total')) {
return $this->total(substr($name, 5));
}
switch ($name) {
case 'years':
return $this->y;
case 'months':
return $this->m;
case 'dayz':
return $this->d;
case 'hours':
return $this->h;
case 'minutes':
return $this->i;
case 'seconds':
return $this->s;
case 'milli':
case 'milliseconds':
return (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND);
case 'micro':
case 'microseconds':
return (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND);
case 'microExcludeMilli':
return (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND;
case 'weeks':
return (int) ($this->d / (int) static::getDaysPerWeek());
case 'daysExcludeWeeks':
case 'dayzExcludeWeeks':
return $this->d % (int) static::getDaysPerWeek();
case 'locale':
return $this->getTranslatorLocale();
default:
throw new UnknownGetterException($name);
}
}
/**
* Get a part of the CarbonInterval object.
*
* @param string $name
*
* @throws UnknownGetterException
*
* @return int|float|string
*/
public function __get($name)
{
return $this->get($name);
}
/**
* Set a part of the CarbonInterval object.
*
* @param string|array $name
* @param int $value
*
* @throws UnknownSetterException
*
* @return $this
*/
public function set($name, $value = null)
{
$properties = \is_array($name) ? $name : [$name => $value];
foreach ($properties as $key => $value) {
switch (Carbon::singularUnit(rtrim($key, 'z'))) {
case 'year':
$this->checkIntegerValue($key, $value);
$this->y = $value;
$this->handleDecimalPart('year', $value, $this->y);
break;
case 'month':
$this->checkIntegerValue($key, $value);
$this->m = $value;
$this->handleDecimalPart('month', $value, $this->m);
break;
case 'week':
$this->checkIntegerValue($key, $value);
$days = $value * (int) static::getDaysPerWeek();
$this->assertSafeForInteger('days total (including weeks)', $days);
$this->d = $days;
$this->handleDecimalPart('day', $days, $this->d);
break;
case 'day':
$this->checkIntegerValue($key, $value);
$this->d = $value;
$this->handleDecimalPart('day', $value, $this->d);
break;
case 'daysexcludeweek':
case 'dayzexcludeweek':
$this->checkIntegerValue($key, $value);
$days = $this->weeks * (int) static::getDaysPerWeek() + $value;
$this->assertSafeForInteger('days total (including weeks)', $days);
$this->d = $days;
$this->handleDecimalPart('day', $days, $this->d);
break;
case 'hour':
$this->checkIntegerValue($key, $value);
$this->h = $value;
$this->handleDecimalPart('hour', $value, $this->h);
break;
case 'minute':
$this->checkIntegerValue($key, $value);
$this->i = $value;
$this->handleDecimalPart('minute', $value, $this->i);
break;
case 'second':
$this->checkIntegerValue($key, $value);
$this->s = $value;
$this->handleDecimalPart('second', $value, $this->s);
break;
case 'milli':
case 'millisecond':
$this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND;
break;
case 'micro':
case 'microsecond':
$this->f = $value / Carbon::MICROSECONDS_PER_SECOND;
break;
default:
if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) {
throw new UnknownSetterException($key);
}
$this->$key = $value;
}
}
return $this;
}
/**
* Set a part of the CarbonInterval object.
*
* @param string $name
* @param int $value
*
* @throws UnknownSetterException
*/
public function __set($name, $value)
{
$this->set($name, $value);
}
/**
* Allow setting of weeks and days to be cumulative.
*
* @param int $weeks Number of weeks to set
* @param int $days Number of days to set
*
* @return static
*/
public function weeksAndDays($weeks, $days)
{
$this->dayz = ($weeks * static::getDaysPerWeek()) + $days;
return $this;
}
/**
* Returns true if the interval is empty for each unit.
*
* @return bool
*/
public function isEmpty()
{
return $this->years === 0 &&
$this->months === 0 &&
$this->dayz === 0 &&
!$this->days &&
$this->hours === 0 &&
$this->minutes === 0 &&
$this->seconds === 0 &&
$this->microseconds === 0;
}
/**
* Register a custom macro.
*
* @example
* ```
* CarbonInterval::macro('twice', function () {
* return $this->times(2);
* });
* echo CarbonInterval::hours(2)->twice();
* ```
*
* @param string $name
* @param object|callable $macro
*
* @return void
*/
public static function macro($name, $macro)
{
static::$macros[$name] = $macro;
}
/**
* Register macros from a mixin object.
*
* @example
* ```
* CarbonInterval::mixin(new class {
* public function daysToHours() {
* return function () {
* $this->hours += $this->days;
* $this->days = 0;
*
* return $this;
* };
* }
* public function hoursToDays() {
* return function () {
* $this->days += $this->hours;
* $this->hours = 0;
*
* return $this;
* };
* }
* });
* echo CarbonInterval::hours(5)->hoursToDays() . "\n";
* echo CarbonInterval::days(5)->daysToHours() . "\n";
* ```
*
* @param object|string $mixin
*
* @throws ReflectionException
*
* @return void
*/
public static function mixin($mixin)
{
static::baseMixin($mixin);
}
/**
* Check if macro is registered.
*
* @param string $name
*
* @return bool
*/
public static function hasMacro($name)
{
return isset(static::$macros[$name]);
}
/**
* Call given macro.
*
* @param string $name
* @param array $parameters
*
* @return mixed
*/
protected function callMacro($name, $parameters)
{
$macro = static::$macros[$name];
if ($macro instanceof Closure) {
$boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class);
return ($boundMacro ?: $macro)(...$parameters);
}
return $macro(...$parameters);
}
/**
* Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day().
*
* Note: This is done using the magic method to allow static and instance methods to
* have the same names.
*
* @param string $method magic method name called
* @param array $parameters parameters list
*
* @throws BadFluentSetterException|Throwable
*
* @return static
*/
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return static::bindMacroContext($this, function () use (&$method, &$parameters) {
return $this->callMacro($method, $parameters);
});
}
$roundedValue = $this->callRoundMethod($method, $parameters);
if ($roundedValue !== null) {
return $roundedValue;
}
if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) {
$value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0);
return $this->{$match['method']}($value, $match['unit']);
}
$value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1);
try {
$this->set($method, $value);
} catch (UnknownSetterException $exception) {
if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) {
throw new BadFluentSetterException($method, 0, $exception);
}
}
return $this;
}
protected function getForHumansInitialVariables($syntax, $short)
{
if (\is_array($syntax)) {
return $syntax;
}
if (\is_int($short)) {
return [
'parts' => $short,
'short' => false,
];
}
if (\is_bool($syntax)) {
return [
'short' => $syntax,
'syntax' => CarbonInterface::DIFF_ABSOLUTE,
];
}
return [];
}
/**
* @param mixed $syntax
* @param mixed $short
* @param mixed $parts
* @param mixed $options
*
* @return array
*/
protected function getForHumansParameters($syntax = null, $short = false, $parts = -1, $options = null)
{
$optionalSpace = ' ';
$default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' ';
$join = $default === '' ? '' : ' ';
$altNumbers = false;
$aUnit = false;
$minimumUnit = 's';
$skip = [];
extract($this->getForHumansInitialVariables($syntax, $short));
$skip = array_map('strtolower', array_filter((array) $skip, static function ($value) {
return \is_string($value) && $value !== '';
}));
if ($syntax === null) {
$syntax = CarbonInterface::DIFF_ABSOLUTE;
}
if ($parts === -1) {
$parts = INF;
}
if ($options === null) {
$options = static::getHumanDiffOptions();
}
if ($join === false) {
$join = ' ';
} elseif ($join === true) {
$join = [
$default,
$this->getTranslationMessage('list.1') ?? $default,
];
}
if ($altNumbers && $altNumbers !== true) {
$language = new Language($this->locale);
$altNumbers = \in_array($language->getCode(), (array) $altNumbers, true);
}
if (\is_array($join)) {
[$default, $last] = $join;
if ($default !== ' ') {
$optionalSpace = '';
}
$join = function ($list) use ($default, $last) {
if (\count($list) < 2) {
return implode('', $list);
}
$end = array_pop($list);
return implode($default, $list).$last.$end;
};
}
if (\is_string($join)) {
if ($join !== ' ') {
$optionalSpace = '';
}
$glue = $join;
$join = function ($list) use ($glue) {
return implode($glue, $list);
};
}
$interpolations = [
':optional-space' => $optionalSpace,
];
return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip];
}
protected static function getRoundingMethodFromOptions(int $options): ?string
{
if ($options & CarbonInterface::ROUND) {
return 'round';
}
if ($options & CarbonInterface::CEIL) {
return 'ceil';
}
if ($options & CarbonInterface::FLOOR) {
return 'floor';
}
return null;
}
/**
* Returns interval values as an array where key are the unit names and values the counts.
*
* @return int[]
*/
public function toArray()
{
return [
'years' => $this->years,
'months' => $this->months,
'weeks' => $this->weeks,
'days' => $this->daysExcludeWeeks,
'hours' => $this->hours,
'minutes' => $this->minutes,
'seconds' => $this->seconds,
'microseconds' => $this->microseconds,
];
}
/**
* Returns interval non-zero values as an array where key are the unit names and values the counts.
*
* @return int[]
*/
public function getNonZeroValues()
{
return array_filter($this->toArray(), 'intval');
}
/**
* Returns interval values as an array where key are the unit names and values the counts
* from the biggest non-zero one the the smallest non-zero one.
*
* @return int[]
*/
public function getValuesSequence()
{
$nonZeroValues = $this->getNonZeroValues();
if ($nonZeroValues === []) {
return [];
}
$keys = array_keys($nonZeroValues);
$firstKey = $keys[0];
$lastKey = $keys[\count($keys) - 1];
$values = [];
$record = false;
foreach ($this->toArray() as $unit => $count) {
if ($unit === $firstKey) {
$record = true;
}
if ($record) {
$values[$unit] = $count;
}
if ($unit === $lastKey) {
$record = false;
}
}
return $values;
}
/**
* Get the current interval in a human readable format in the current locale.
*
* @example
* ```
* echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n";
* echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n";
* echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n";
* echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n";
* echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n";
* echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n";
* ```
*
* @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains:
* - 'syntax' entry (see below)
* - 'short' entry (see below)
* - 'parts' entry (see below)
* - 'options' entry (see below)
* - 'skip' entry, list of units to skip (array of strings or a single string,
* ` it can be the unit name (singular or plural) or its shortcut
* ` (y, m, w, d, h, min, s, ms, µs).
* - 'aUnit' entry, prefer "an hour" over "1 hour" if true
* - 'join' entry determines how to join multiple parts of the string
* ` - if $join is a string, it's used as a joiner glue
* ` - if $join is a callable/closure, it get the list of string and should return a string
* ` - if $join is an array, the first item will be the default glue, and the second item
* ` will be used instead of the glue for the last item
* ` - if $join is true, it will be guessed from the locale ('list' translation file entry)
* ` - if $join is missing, a space will be used as glue
* - 'minimumUnit' entry determines the smallest unit of time to display can be long or
* ` short form of the units, e.g. 'hour' or 'h' (default value: s)
* if int passed, it add modifiers:
* Possible values:
* - CarbonInterface::DIFF_ABSOLUTE no modifiers
* - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier
* - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier
* Default value: CarbonInterface::DIFF_ABSOLUTE
* @param bool $short displays short format of time units
* @param int $parts maximum number of parts to display (default value: -1: no limits)
* @param int $options human diff options
*
* @throws Exception
*
* @return string
*/
public function forHumans($syntax = null, $short = false, $parts = -1, $options = null)
{
[$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip] = $this
->getForHumansParameters($syntax, $short, $parts, $options);
$interval = [];
$syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE);
$absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE;
$relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW;
$count = 1;
$unit = $short ? 's' : 'second';
$isFuture = $this->invert === 1;
$transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before');
$declensionMode = null;
/** @var \Symfony\Component\Translation\Translator $translator */
$translator = $this->getLocalTranslator();
$handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) {
if (!$absolute) {
$declensionMode = $declensionMode ?? $this->translate($transId.'_mode');
if ($this->needsDeclension($declensionMode, $index, $parts)) {
// Some languages have special pluralization for past and future tense.
$key = $unit.'_'.$transId;
$result = $this->translate($key, $interpolations, $count, $translator, $altNumbers);
if ($result !== $key) {
return $result;
}
}
}
$result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers);
if ($result !== $unit) {
return $result;
}
return null;
};
$intervalValues = $this;
$method = static::getRoundingMethodFromOptions($options);
if ($method) {
$previousCount = INF;
while (
\count($intervalValues->getNonZeroValues()) > $parts &&
($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1
) {
$index = min($count, $previousCount - 1) - 2;
if ($index < 0) {
break;
}
$intervalValues = $this->copy()->roundUnit(
$keys[$index],
1,
$method
);
$previousCount = $count;
}
}
$diffIntervalArray = [
['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'],
['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'],
['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'],
['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'],
['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'],
['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'],
['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'],
['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'],
['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'],
];
if (!empty($skip)) {
foreach ($diffIntervalArray as $index => &$unitData) {
$nextIndex = $index + 1;
if ($unitData['value'] &&
isset($diffIntervalArray[$nextIndex]) &&
\count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip))
) {
$diffIntervalArray[$nextIndex]['value'] += $unitData['value'] *
self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']);
$unitData['value'] = 0;
}
}
}
$transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) {
$count = $unitData['value'];
if ($short) {
$result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts);
if ($result !== null) {
return $result;
}
} elseif ($aUnit) {
$result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts);
if ($result !== null) {
return $result;
}
}
if (!$absolute) {
return $handleDeclensions($unitData['unit'], $count, $index, $parts);
}
return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers);
};
$fallbackUnit = ['second', 's'];
foreach ($diffIntervalArray as $diffIntervalData) {
if ($diffIntervalData['value'] > 0) {
$unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit'];
$count = $diffIntervalData['value'];
$interval[] = [$short, $diffIntervalData];
} elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) {
break;
}
// break the loop after we get the required number of parts in array
if (\count($interval) >= $parts) {
break;
}
// break the loop after we have reached the minimum unit
if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) {
$fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']];
break;
}
}
$actualParts = \count($interval);
foreach ($interval as $index => &$item) {
$item = $transChoice($item[0], $item[1], $index, $actualParts);
}
if (\count($interval) === 0) {
if ($relativeToNow && $options & CarbonInterface::JUST_NOW) {
$key = 'diff_now';
$translation = $this->translate($key, $interpolations, null, $translator);
if ($translation !== $key) {
return $translation;
}
}
$count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0;
$unit = $fallbackUnit[$short ? 1 : 0];
$interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers);
}
// join the interval parts by a space
$time = $join($interval);
unset($diffIntervalArray, $interval);
if ($absolute) {
return $time;
}
$isFuture = $this->invert === 1;
$transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before');
if ($parts === 1) {
if ($relativeToNow && $unit === 'day') {
if ($count === 1 && $options & CarbonInterface::ONE_DAY_WORDS) {
$key = $isFuture ? 'diff_tomorrow' : 'diff_yesterday';
$translation = $this->translate($key, $interpolations, null, $translator);
if ($translation !== $key) {
return $translation;
}
}
if ($count === 2 && $options & CarbonInterface::TWO_DAY_WORDS) {
$key = $isFuture ? 'diff_after_tomorrow' : 'diff_before_yesterday';
$translation = $this->translate($key, $interpolations, null, $translator);
if ($translation !== $key) {
return $translation;
}
}
}
$aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null;
$time = $aTime ?: $handleDeclensions($unit, $count) ?: $time;
}
$time = [':time' => $time];
return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator);
}
/**
* Format the instance as a string using the forHumans() function.
*
* @throws Exception
*
* @return string
*/
public function __toString()
{
$format = $this->localToStringFormat ?? static::$toStringFormat;
if (!$format) {
return $this->forHumans();
}
if ($format instanceof Closure) {
return $format($this);
}
return $this->format($format);
}
/**
* Return native DateInterval PHP object matching the current instance.
*
* @example
* ```
* var_dump(CarbonInterval::hours(2)->toDateInterval());
* ```
*
* @return DateInterval
*/
public function toDateInterval()
{
return self::castIntervalToClass($this, DateInterval::class);
}
/**
* Convert the interval to a CarbonPeriod.
*
* @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings.
*
* @return CarbonPeriod
*/
public function toPeriod(...$params)
{
if ($this->tzName) {
$tz = \is_string($this->tzName) ? new DateTimeZone($this->tzName) : $this->tzName;
if ($tz instanceof DateTimeZone) {
array_unshift($params, $tz);
}
}
return CarbonPeriod::create($this, ...$params);
}
/**
* Invert the interval.
*
* @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used
* as the new value of the ->invert property.
*
* @return $this
*/
public function invert($inverted = null)
{
$this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0;
return $this;
}
protected function solveNegativeInterval()
{
if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) {
$this->years *= -1;
$this->months *= -1;
$this->dayz *= -1;
$this->hours *= -1;
$this->minutes *= -1;
$this->seconds *= -1;
$this->microseconds *= -1;
$this->invert();
}
return $this;
}
/**
* Add the passed interval to the current instance.
*
* @param string|DateInterval $unit
* @param int|float $value
*
* @return $this
*/
public function add($unit, $value = 1)
{
if (is_numeric($unit)) {
[$value, $unit] = [$unit, $value];
}
if (\is_string($unit) && !preg_match('/^\s*\d/', $unit)) {
$unit = "$value $unit";
$value = 1;
}
$interval = static::make($unit);
if (!$interval) {
throw new InvalidIntervalException('This type of data cannot be added/subtracted.');
}
if ($value !== 1) {
$interval->times($value);
}
$sign = ($this->invert === 1) !== ($interval->invert === 1) ? -1 : 1;
$this->years += $interval->y * $sign;
$this->months += $interval->m * $sign;
$this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign;
$this->hours += $interval->h * $sign;
$this->minutes += $interval->i * $sign;
$this->seconds += $interval->s * $sign;
$this->microseconds += $interval->microseconds * $sign;
$this->solveNegativeInterval();
return $this;
}
/**
* Subtract the passed interval to the current instance.
*
* @param string|DateInterval $unit
* @param int|float $value
*
* @return $this
*/
public function sub($unit, $value = 1)
{
if (is_numeric($unit)) {
[$value, $unit] = [$unit, $value];
}
return $this->add($unit, -(float) $value);
}
/**
* Subtract the passed interval to the current instance.
*
* @param string|DateInterval $unit
* @param int|float $value
*
* @return $this
*/
public function subtract($unit, $value = 1)
{
return $this->sub($unit, $value);
}
/**
* Add given parameters to the current interval.
*
* @param int $years
* @param int $months
* @param int|float $weeks
* @param int|float $days
* @param int|float $hours
* @param int|float $minutes
* @param int|float $seconds
* @param int|float $microseconds
*
* @return $this
*/
public function plus(
$years = 0,
$months = 0,
$weeks = 0,
$days = 0,
$hours = 0,
$minutes = 0,
$seconds = 0,
$microseconds = 0
): self {
return $this->add("
$years years $months months $weeks weeks $days days
$hours hours $minutes minutes $seconds seconds $microseconds microseconds
");
}
/**
* Add given parameters to the current interval.
*
* @param int $years
* @param int $months
* @param int|float $weeks
* @param int|float $days
* @param int|float $hours
* @param int|float $minutes
* @param int|float $seconds
* @param int|float $microseconds
*
* @return $this
*/
public function minus(
$years = 0,
$months = 0,
$weeks = 0,
$days = 0,
$hours = 0,
$minutes = 0,
$seconds = 0,
$microseconds = 0
): self {
return $this->sub("
$years years $months months $weeks weeks $days days
$hours hours $minutes minutes $seconds seconds $microseconds microseconds
");
}
/**
* Multiply current instance given number of times. times() is naive, it multiplies each unit
* (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded
* separately for each unit.
*
* Use times() when you want a fast and approximated calculation that does not cascade units.
*
* For a precise and cascaded calculation,
*
* @see multiply()
*
* @param float|int $factor
*
* @return $this
*/
public function times($factor)
{
if ($factor < 0) {
$this->invert = $this->invert ? 0 : 1;
$factor = -$factor;
}
$this->years = (int) round($this->years * $factor);
$this->months = (int) round($this->months * $factor);
$this->dayz = (int) round($this->dayz * $factor);
$this->hours = (int) round($this->hours * $factor);
$this->minutes = (int) round($this->minutes * $factor);
$this->seconds = (int) round($this->seconds * $factor);
$this->microseconds = (int) round($this->microseconds * $factor);
return $this;
}
/**
* Divide current instance by a given divider. shares() is naive, it divides each unit separately
* and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours
* and 7 minutes.
*
* Use shares() when you want a fast and approximated calculation that does not cascade units.
*
* For a precise and cascaded calculation,
*
* @see divide()
*
* @param float|int $divider
*
* @return $this
*/
public function shares($divider)
{
return $this->times(1 / $divider);
}
protected function copyProperties(self $interval, $ignoreSign = false)
{
$this->years = $interval->years;
$this->months = $interval->months;
$this->dayz = $interval->dayz;
$this->hours = $interval->hours;
$this->minutes = $interval->minutes;
$this->seconds = $interval->seconds;
$this->microseconds = $interval->microseconds;
if (!$ignoreSign) {
$this->invert = $interval->invert;
}
return $this;
}
/**
* Multiply and cascade current instance by a given factor.
*
* @param float|int $factor
*
* @return $this
*/
public function multiply($factor)
{
if ($factor < 0) {
$this->invert = $this->invert ? 0 : 1;
$factor = -$factor;
}
$yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision
if ($yearPart) {
$this->years -= $yearPart / $factor;
}
return $this->copyProperties(
static::create($yearPart)
->microseconds(abs($this->totalMicroseconds) * $factor)
->cascade(),
true
);
}
/**
* Divide and cascade current instance by a given divider.
*
* @param float|int $divider
*
* @return $this
*/
public function divide($divider)
{
return $this->multiply(1 / $divider);
}
/**
* Get the interval_spec string of a date interval.
*
* @param DateInterval $interval
*
* @return string
*/
public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = [])
{
$date = array_filter([
static::PERIOD_YEARS => abs($interval->y),
static::PERIOD_MONTHS => abs($interval->m),
static::PERIOD_DAYS => abs($interval->d),
]);
if (
$interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH &&
(!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) &&
(!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip)))
) {
$date = [
static::PERIOD_DAYS => abs($interval->days),
];
}
$seconds = abs($interval->s);
if ($microseconds && $interval->f > 0) {
$seconds = sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000);
}
$time = array_filter([
static::PERIOD_HOURS => abs($interval->h),
static::PERIOD_MINUTES => abs($interval->i),
static::PERIOD_SECONDS => $seconds,
]);
$specString = static::PERIOD_PREFIX;
foreach ($date as $key => $value) {
$specString .= $value.$key;
}
if (\count($time) > 0) {
$specString .= static::PERIOD_TIME_PREFIX;
foreach ($time as $key => $value) {
$specString .= $value.$key;
}
}
return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString;
}
/**
* Get the interval_spec string.
*
* @return string
*/
public function spec(bool $microseconds = false)
{
return static::getDateIntervalSpec($this, $microseconds);
}
/**
* Comparing 2 date intervals.
*
* @param DateInterval $first
* @param DateInterval $second
*
* @return int
*/
public static function compareDateIntervals(DateInterval $first, DateInterval $second)
{
$current = Carbon::now();
$passed = $current->avoidMutation()->add($second);
$current->add($first);
if ($current < $passed) {
return -1;
}
if ($current > $passed) {
return 1;
}
return 0;
}
/**
* Comparing with passed interval.
*
* @param DateInterval $interval
*
* @return int
*/
public function compare(DateInterval $interval)
{
return static::compareDateIntervals($this, $interval);
}
private function invertCascade(array $values)
{
return $this->set(array_map(function ($value) {
return -$value;
}, $values))->doCascade(true)->invert();
}
private function doCascade(bool $deep)
{
$originalData = $this->toArray();
$originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond());
$originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond();
$originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek());
$originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek());
unset($originalData['days']);
$newData = $originalData;
$previous = [];
foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) {
foreach (['source', 'target'] as $key) {
if ($$key === 'dayz') {
$$key = 'daysExcludeWeeks';
}
}
$value = $newData[$source];
$modulo = fmod($factor + fmod($value, $factor), $factor);
$newData[$source] = $modulo;
$newData[$target] += ($value - $modulo) / $factor;
$decimalPart = fmod($newData[$source], 1);
if ($decimalPart !== 0.0) {
$unit = $source;
foreach ($previous as [$subUnit, $subFactor]) {
$newData[$unit] -= $decimalPart;
$newData[$subUnit] += $decimalPart * $subFactor;
$decimalPart = fmod($newData[$subUnit], 1);
if ($decimalPart === 0.0) {
break;
}
$unit = $subUnit;
}
}
array_unshift($previous, [$source, $factor]);
}
$positive = null;
if (!$deep) {
foreach ($newData as $value) {
if ($value) {
if ($positive === null) {
$positive = ($value > 0);
continue;
}
if (($value > 0) !== $positive) {
return $this->invertCascade($originalData)
->solveNegativeInterval();
}
}
}
}
return $this->set($newData)
->solveNegativeInterval();
}
/**
* Convert overflowed values into bigger units.
*
* @return $this
*/
public function cascade()
{
return $this->doCascade(false);
}
public function hasNegativeValues(): bool
{
foreach ($this->toArray() as $value) {
if ($value < 0) {
return true;
}
}
return false;
}
public function hasPositiveValues(): bool
{
foreach ($this->toArray() as $value) {
if ($value > 0) {
return true;
}
}
return false;
}
/**
* Get amount of given unit equivalent to the interval.
*
* @param string $unit
*
* @throws UnknownUnitException|UnitNotConfiguredException
*
* @return float
*/
public function total($unit)
{
$realUnit = $unit = strtolower($unit);
if (\in_array($unit, ['days', 'weeks'])) {
$realUnit = 'dayz';
} elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) {
throw new UnknownUnitException($unit);
}
$result = 0;
$cumulativeFactor = 0;
$unitFound = false;
$factors = self::getFlipCascadeFactors();
$daysPerWeek = (int) static::getDaysPerWeek();
$values = [
'years' => $this->years,
'months' => $this->months,
'weeks' => (int) ($this->d / $daysPerWeek),
'dayz' => fmod($this->d, $daysPerWeek),
'hours' => $this->hours,
'minutes' => $this->minutes,
'seconds' => $this->seconds,
'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND),
'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND,
];
if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') {
$values['dayz'] += $values['weeks'] * $daysPerWeek;
$values['weeks'] = 0;
}
foreach ($factors as $source => [$target, $factor]) {
if ($source === $realUnit) {
$unitFound = true;
$value = $values[$source];
$result += $value;
$cumulativeFactor = 1;
}
if ($factor === false) {
if ($unitFound) {
break;
}
$result = 0;
$cumulativeFactor = 0;
continue;
}
if ($target === $realUnit) {
$unitFound = true;
}
if ($cumulativeFactor) {
$cumulativeFactor *= $factor;
$result += $values[$target] * $cumulativeFactor;
continue;
}
$value = $values[$source];
$result = ($result + $value) / $factor;
}
if (isset($target) && !$cumulativeFactor) {
$result += $values[$target];
}
if (!$unitFound) {
throw new UnitNotConfiguredException($unit);
}
if ($this->invert) {
$result *= -1;
}
if ($unit === 'weeks') {
$result /= $daysPerWeek;
}
// Cast as int numbers with no decimal part
return fmod($result, 1) === 0.0 ? (int) $result : $result;
}
/**
* Determines if the instance is equal to another
*
* @param CarbonInterval|DateInterval|mixed $interval
*
* @see equalTo()
*
* @return bool
*/
public function eq($interval): bool
{
return $this->equalTo($interval);
}
/**
* Determines if the instance is equal to another
*
* @param CarbonInterval|DateInterval|mixed $interval
*
* @return bool
*/
public function equalTo($interval): bool
{
$interval = $this->resolveInterval($interval);
return $interval !== null && $this->totalMicroseconds === $interval->totalMicroseconds;
}
/**
* Determines if the instance is not equal to another
*
* @param CarbonInterval|DateInterval|mixed $interval
*
* @see notEqualTo()
*
* @return bool
*/
public function ne($interval): bool
{
return $this->notEqualTo($interval);
}
/**
* Determines if the instance is not equal to another
*
* @param CarbonInterval|DateInterval|mixed $interval
*
* @return bool
*/
public function notEqualTo($interval): bool
{
return !$this->eq($interval);
}
/**
* Determines if the instance is greater (longer) than another
*
* @param CarbonInterval|DateInterval|mixed $interval
*
* @see greaterThan()
*
* @return bool
*/
public function gt($interval): bool
{
return $this->greaterThan($interval);
}
/**
* Determines if the instance is greater (longer) than another
*
* @param CarbonInterval|DateInterval|mixed $interval
*
* @return bool
*/
public function greaterThan($interval): bool
{
$interval = $this->resolveInterval($interval);
return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds;
}
/**
* Determines if the instance is greater (longer) than or equal to another
*
* @param CarbonInterval|DateInterval|mixed $interval
*
* @see greaterThanOrEqualTo()
*
* @return bool
*/
public function gte($interval): bool
{
return $this->greaterThanOrEqualTo($interval);
}
/**
* Determines if the instance is greater (longer) than or equal to another
*
* @param CarbonInterval|DateInterval|mixed $interval
*
* @return bool
*/
public function greaterThanOrEqualTo($interval): bool
{
return $this->greaterThan($interval) || $this->equalTo($interval);
}
/**
* Determines if the instance is less (shorter) than another
*
* @param CarbonInterval|DateInterval|mixed $interval
*
* @see lessThan()
*
* @return bool
*/
public function lt($interval): bool
{
return $this->lessThan($interval);
}
/**
* Determines if the instance is less (shorter) than another
*
* @param CarbonInterval|DateInterval|mixed $interval
*
* @return bool
*/
public function lessThan($interval): bool
{
$interval = $this->resolveInterval($interval);
return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds;
}
/**
* Determines if the instance is less (shorter) than or equal to another
*
* @param CarbonInterval|DateInterval|mixed $interval
*
* @see lessThanOrEqualTo()
*
* @return bool
*/
public function lte($interval): bool
{
return $this->lessThanOrEqualTo($interval);
}
/**
* Determines if the instance is less (shorter) than or equal to another
*
* @param CarbonInterval|DateInterval|mixed $interval
*
* @return bool
*/
public function lessThanOrEqualTo($interval): bool
{
return $this->lessThan($interval) || $this->equalTo($interval);
}
/**
* Determines if the instance is between two others.
*
* The third argument allow you to specify if bounds are included or not (true by default)
* but for when you including/excluding bounds may produce different results in your application,
* we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead.
*
* @example
* ```
* CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true
* CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false
* CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true
* CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false
* ```
*
* @param CarbonInterval|DateInterval|mixed $interval1
* @param CarbonInterval|DateInterval|mixed $interval2
* @param bool $equal Indicates if an equal to comparison should be done
*
* @return bool
*/
public function between($interval1, $interval2, $equal = true): bool
{
return $equal
? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2)
: $this->greaterThan($interval1) && $this->lessThan($interval2);
}
/**
* Determines if the instance is between two others, bounds excluded.
*
* @example
* ```
* CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true
* CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false
* CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true
* ```
*
* @param CarbonInterval|DateInterval|mixed $interval1
* @param CarbonInterval|DateInterval|mixed $interval2
*
* @return bool
*/
public function betweenIncluded($interval1, $interval2): bool
{
return $this->between($interval1, $interval2, true);
}
/**
* Determines if the instance is between two others, bounds excluded.
*
* @example
* ```
* CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true
* CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false
* CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false
* ```
*
* @param CarbonInterval|DateInterval|mixed $interval1
* @param CarbonInterval|DateInterval|mixed $interval2
*
* @return bool
*/
public function betweenExcluded($interval1, $interval2): bool
{
return $this->between($interval1, $interval2, false);
}
/**
* Determines if the instance is between two others
*
* @example
* ```
* CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true
* CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false
* CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true
* CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false
* ```
*
* @param CarbonInterval|DateInterval|mixed $interval1
* @param CarbonInterval|DateInterval|mixed $interval2
* @param bool $equal Indicates if an equal to comparison should be done
*
* @return bool
*/
public function isBetween($interval1, $interval2, $equal = true): bool
{
return $this->between($interval1, $interval2, $equal);
}
/**
* Round the current instance at the given unit with given precision if specified and the given function.
*
* @param string $unit
* @param float|int|string|DateInterval|null $precision
* @param string $function
*
* @throws Exception
*
* @return $this
*/
public function roundUnit($unit, $precision = 1, $function = 'round')
{
if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) {
$value = $function($this->total($unit) / $precision) * $precision;
$inverted = $value < 0;
return $this->copyProperties(self::fromString(
number_format(abs($value), 12, '.', '').' '.$unit
)->invert($inverted)->cascade());
}
$base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC')
->roundUnit($unit, $precision, $function);
$next = $base->add($this);
$inverted = $next < $base;
if ($inverted) {
$next = $base->sub($this);
}
$this->copyProperties(
$next
->roundUnit($unit, $precision, $function)
->diffAsCarbonInterval($base)
);
return $this->invert($inverted);
}
/**
* Truncate the current instance at the given unit with given precision if specified.
*
* @param string $unit
* @param float|int|string|DateInterval|null $precision
*
* @throws Exception
*
* @return $this
*/
public function floorUnit($unit, $precision = 1)
{
return $this->roundUnit($unit, $precision, 'floor');
}
/**
* Ceil the current instance at the given unit with given precision if specified.
*
* @param string $unit
* @param float|int|string|DateInterval|null $precision
*
* @throws Exception
*
* @return $this
*/
public function ceilUnit($unit, $precision = 1)
{
return $this->roundUnit($unit, $precision, 'ceil');
}
/**
* Round the current instance second with given precision if specified.
*
* @param float|int|string|DateInterval|null $precision
* @param string $function
*
* @throws Exception
*
* @return $this
*/
public function round($precision = 1, $function = 'round')
{
return $this->roundWith($precision, $function);
}
/**
* Round the current instance second with given precision if specified.
*
* @param float|int|string|DateInterval|null $precision
*
* @throws Exception
*
* @return $this
*/
public function floor($precision = 1)
{
return $this->round($precision, 'floor');
}
/**
* Ceil the current instance second with given precision if specified.
*
* @param float|int|string|DateInterval|null $precision
*
* @throws Exception
*
* @return $this
*/
public function ceil($precision = 1)
{
return $this->round($precision, 'ceil');
}
private function needsDeclension(string $mode, int $index, int $parts): bool
{
switch ($mode) {
case 'last':
return $index === $parts - 1;
default:
return true;
}
}
private function checkIntegerValue(string $name, $value)
{
if (\is_int($value)) {
return;
}
$this->assertSafeForInteger($name, $value);
if (\is_float($value) && (((float) (int) $value) === $value)) {
return;
}
if (!self::$floatSettersEnabled) {
$type = \gettype($value);
@trigger_error(
"Since 2.70.0, it's deprecated to pass $type value for $name.\n".
"It's truncated when stored as an integer interval unit.\n".
"From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n".
"- To maintain the current behavior, use explicit cast: $name((int) \$value)\n".
"- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n",
\E_USER_DEPRECATED
);
}
}
/**
* Throw an exception if precision loss when storing the given value as an integer would be >= 1.0.
*/
private function assertSafeForInteger(string $name, $value)
{
if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) {
throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value);
}
}
private function handleDecimalPart(string $unit, $value, $integerValue)
{
if (self::$floatSettersEnabled) {
$floatValue = (float) $value;
$base = (float) $integerValue;
if ($floatValue === $base) {
return;
}
$units = [
'y' => 'year',
'm' => 'month',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
];
$upper = true;
foreach ($units as $property => $name) {
if ($name === $unit) {
$upper = false;
continue;
}
if (!$upper && $this->$property !== 0) {
throw new RuntimeException(
"You cannot set $unit to a float value as $name would be overridden, ".
'set it first to 0 explicitly if you really want to erase its value'
);
}
}
$this->add($unit, $floatValue - $base);
}
}
}