/
Carbon.php
4812 lines (4306 loc) · 124 KB
/
Carbon.php
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
<?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\InvalidDateException;
use Closure;
use DatePeriod;
use DateTime;
use DateTimeInterface;
use DateTimeZone;
use InvalidArgumentException;
use JsonSerializable;
use Symfony\Component\Translation\TranslatorInterface;
/**
* A simple API extension for DateTime
*
* @property int $year
* @property int $yearIso
* @property int $month
* @property int $day
* @property int $hour
* @property int $minute
* @property int $second
* @property int $timestamp seconds since the Unix Epoch
* @property \DateTimeZone $timezone the current timezone
* @property \DateTimeZone $tz alias of timezone
* @property-read int $micro
* @property-read int $dayOfWeek 0 (for Sunday) through 6 (for Saturday)
* @property-read int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday)
* @property-read int $dayOfYear 0 through 365
* @property-read int $weekOfMonth 1 through 5
* @property-read int $weekNumberInMonth 1 through 5
* @property-read int $weekOfYear ISO-8601 week number of year, weeks starting on Monday
* @property-read int $daysInMonth number of days in the given month
* @property-read int $age does a diffInYears() with default parameters
* @property-read int $quarter the quarter of this instance, 1 - 4
* @property-read int $offset the timezone offset in seconds from UTC
* @property-read int $offsetHours the timezone offset in hours from UTC
* @property-read bool $dst daylight savings time indicator, true if DST, false otherwise
* @property-read bool $local checks if the timezone is local, true if local, false otherwise
* @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise
* @property-read string $timezoneName
* @property-read string $tzName
* @property-read string $englishDayOfWeek the day of week in English
* @property-read string $shortEnglishDayOfWeek the abbreviated day of week in English
* @property-read string $englishMonth the day of week in English
* @property-read string $shortEnglishMonth the abbreviated day of week in English
* @property-read string $localeDayOfWeek the day of week in current locale LC_TIME
* @property-read string $shortLocaleDayOfWeek the abbreviated day of week in current locale LC_TIME
* @property-read string $localeMonth the month in current locale LC_TIME
* @property-read string $shortLocaleMonth the abbreviated month in current locale LC_TIME
*/
class Carbon extends DateTime implements JsonSerializable
{
const NO_ZERO_DIFF = 01;
const JUST_NOW = 02;
const ONE_DAY_WORDS = 04;
const TWO_DAY_WORDS = 010;
/**
* The day constants.
*/
const SUNDAY = 0;
const MONDAY = 1;
const TUESDAY = 2;
const WEDNESDAY = 3;
const THURSDAY = 4;
const FRIDAY = 5;
const SATURDAY = 6;
/**
* Names of days of the week.
*
* @var array
*/
protected static $days = array(
self::SUNDAY => 'Sunday',
self::MONDAY => 'Monday',
self::TUESDAY => 'Tuesday',
self::WEDNESDAY => 'Wednesday',
self::THURSDAY => 'Thursday',
self::FRIDAY => 'Friday',
self::SATURDAY => 'Saturday',
);
/**
* Number of X in Y.
*/
const YEARS_PER_CENTURY = 100;
const YEARS_PER_DECADE = 10;
const MONTHS_PER_YEAR = 12;
const MONTHS_PER_QUARTER = 3;
const WEEKS_PER_YEAR = 52;
const WEEKS_PER_MONTH = 4;
const DAYS_PER_WEEK = 7;
const HOURS_PER_DAY = 24;
const MINUTES_PER_HOUR = 60;
const SECONDS_PER_MINUTE = 60;
/**
* RFC7231 DateTime format.
*
* @var string
*/
const RFC7231_FORMAT = 'D, d M Y H:i:s \G\M\T';
/**
* Default format to use for __toString method when type juggling occurs.
*
* @var string
*/
const DEFAULT_TO_STRING_FORMAT = 'Y-m-d H:i:s';
/**
* Format for converting mocked time, includes microseconds.
*
* @var string
*/
const MOCK_DATETIME_FORMAT = 'Y-m-d H:i:s.u';
/**
* Customizable PHP_INT_SIZE override.
*
* @var int
*/
public static $PHPIntSize = PHP_INT_SIZE;
/**
* Format to use for __toString method when type juggling occurs.
*
* @var string
*/
protected static $toStringFormat = self::DEFAULT_TO_STRING_FORMAT;
/**
* First day of week.
*
* @var int
*/
protected static $weekStartsAt = self::MONDAY;
/**
* Last day of week.
*
* @var int
*/
protected static $weekEndsAt = self::SUNDAY;
/**
* Days of weekend.
*
* @var array
*/
protected static $weekendDays = array(
self::SATURDAY,
self::SUNDAY,
);
/**
* Midday/noon hour.
*
* @var int
*/
protected static $midDayAt = 12;
/**
* Format regex patterns.
*
* @var array
*/
protected static $regexFormats = array(
'd' => '(3[01]|[12][0-9]|0[1-9])',
'D' => '([a-zA-Z]{3})',
'j' => '([123][0-9]|[1-9])',
'l' => '([a-zA-Z]{2,})',
'N' => '([1-7])',
'S' => '([a-zA-Z]{2})',
'w' => '([0-6])',
'z' => '(36[0-5]|3[0-5][0-9]|[12][0-9]{2}|[1-9]?[0-9])',
'W' => '(5[012]|[1-4][0-9]|[1-9])',
'F' => '([a-zA-Z]{2,})',
'm' => '(1[012]|0[1-9])',
'M' => '([a-zA-Z]{3})',
'n' => '(1[012]|[1-9])',
't' => '(2[89]|3[01])',
'L' => '(0|1)',
'o' => '([1-9][0-9]{0,4})',
'Y' => '([1-9][0-9]{0,4})',
'y' => '([0-9]{2})',
'a' => '(am|pm)',
'A' => '(AM|PM)',
'B' => '([0-9]{3})',
'g' => '(1[012]|[1-9])',
'G' => '(2[0-3]|1?[0-9])',
'h' => '(1[012]|0[1-9])',
'H' => '(2[0-3]|[01][0-9])',
'i' => '([0-5][0-9])',
's' => '([0-5][0-9])',
'u' => '([0-9]{1,6})',
'v' => '([0-9]{1,3})',
'e' => '([a-zA-Z]{1,5})|([a-zA-Z]*\/[a-zA-Z]*)',
'I' => '(0|1)',
'O' => '([\+\-](1[012]|0[0-9])[0134][05])',
'P' => '([\+\-](1[012]|0[0-9]):[0134][05])',
'T' => '([a-zA-Z]{1,5})',
'Z' => '(-?[1-5]?[0-9]{1,4})',
'U' => '([0-9]*)',
// The formats below are combinations of the above formats.
'c' => '(([1-9][0-9]{0,4})\-(1[012]|0[1-9])\-(3[01]|[12][0-9]|0[1-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])[\+\-](1[012]|0[0-9]):([0134][05]))', // Y-m-dTH:i:sP
'r' => '(([a-zA-Z]{3}), ([123][0-9]|[1-9]) ([a-zA-Z]{3}) ([1-9][0-9]{0,4}) (2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]) [\+\-](1[012]|0[0-9])([0134][05]))', // D, j M Y H:i:s O
);
/**
* A test Carbon instance to be returned when now instances are created.
*
* @var \Carbon\Carbon
*/
protected static $testNow;
/**
* A translator to ... er ... translate stuff.
*
* @var \Symfony\Component\Translation\TranslatorInterface
*/
protected static $translator;
/**
* The errors that can occur.
*
* @var array
*/
protected static $lastErrors;
/**
* The custom Carbon JSON serializer.
*
* @var callable|null
*/
protected static $serializer;
/**
* The registered string macros.
*
* @var array
*/
protected static $localMacros = array();
/**
* Will UTF8 encoding be used to print localized date/time ?
*
* @var bool
*/
protected static $utf8 = false;
/**
* Add microseconds to now on PHP < 7.1 and 7.1.3. true by default.
*
* @var bool
*/
protected static $microsecondsFallback = true;
/**
* Indicates if months should be calculated with overflow.
*
* @var bool
*/
protected static $monthsOverflow = true;
/**
* Indicates if years should be calculated with overflow.
*
* @var bool
*/
protected static $yearsOverflow = true;
/**
* Indicates if years are compared with month by default so isSameMonth and isSameQuarter have $ofSameYear set
* to true by default.
*
* @var bool
*/
protected static $compareYearWithMonth = false;
/**
* Options for diffForHumans().
*
* @var int
*/
protected static $humanDiffOptions = self::NO_ZERO_DIFF;
/**
* @param int $humanDiffOptions
*/
public static function setHumanDiffOptions($humanDiffOptions)
{
static::$humanDiffOptions = $humanDiffOptions;
}
/**
* @param int $humanDiffOption
*/
public static function enableHumanDiffOption($humanDiffOption)
{
static::$humanDiffOptions = static::getHumanDiffOptions() | $humanDiffOption;
}
/**
* @param int $humanDiffOption
*/
public static function disableHumanDiffOption($humanDiffOption)
{
static::$humanDiffOptions = static::getHumanDiffOptions() & ~$humanDiffOption;
}
/**
* @return int
*/
public static function getHumanDiffOptions()
{
return static::$humanDiffOptions;
}
/**
* Add microseconds to now on PHP < 7.1 and 7.1.3 if set to true,
* let microseconds to 0 on those PHP versions if false.
*
* @param bool $microsecondsFallback
*/
public static function useMicrosecondsFallback($microsecondsFallback = true)
{
static::$microsecondsFallback = $microsecondsFallback;
}
/**
* Return true if microseconds fallback on PHP < 7.1 and 7.1.3 is
* enabled. false if disabled.
*
* @return bool
*/
public static function isMicrosecondsFallbackEnabled()
{
return static::$microsecondsFallback;
}
/**
* Indicates if months should be calculated with overflow.
*
* @param bool $monthsOverflow
*
* @return void
*/
public static function useMonthsOverflow($monthsOverflow = true)
{
static::$monthsOverflow = $monthsOverflow;
}
/**
* Reset the month overflow behavior.
*
* @return void
*/
public static function resetMonthsOverflow()
{
static::$monthsOverflow = true;
}
/**
* Get the month overflow behavior.
*
* @return bool
*/
public static function shouldOverflowMonths()
{
return static::$monthsOverflow;
}
/**
* Indicates if years should be calculated with overflow.
*
* @param bool $yearsOverflow
*
* @return void
*/
public static function useYearsOverflow($yearsOverflow = true)
{
static::$yearsOverflow = $yearsOverflow;
}
/**
* Reset the month overflow behavior.
*
* @return void
*/
public static function resetYearsOverflow()
{
static::$yearsOverflow = true;
}
/**
* Get the month overflow behavior.
*
* @return bool
*/
public static function shouldOverflowYears()
{
return static::$yearsOverflow;
}
/**
* Get the month comparison default behavior.
*
* @return bool
*/
public static function compareYearWithMonth($compareYearWithMonth = true)
{
static::$compareYearWithMonth = $compareYearWithMonth;
}
/**
* Get the month comparison default behavior.
*
* @return bool
*/
public static function shouldCompareYearWithMonth()
{
return static::$compareYearWithMonth;
}
/**
* Creates a DateTimeZone from a string, DateTimeZone or integer offset.
*
* @param \DateTimeZone|string|int|null $object
*
* @throws \InvalidArgumentException
*
* @return \DateTimeZone
*/
protected static function safeCreateDateTimeZone($object)
{
if ($object === null) {
// Don't return null... avoid Bug #52063 in PHP <5.3.6
return new DateTimeZone(date_default_timezone_get());
}
if ($object instanceof DateTimeZone) {
return $object;
}
if (is_numeric($object)) {
$tzName = timezone_name_from_abbr(null, $object * 3600, true);
if ($tzName === false) {
throw new InvalidArgumentException('Unknown or bad timezone ('.$object.')');
}
$object = $tzName;
}
$tz = @timezone_open($object = (string) $object);
if ($tz !== false) {
return $tz;
}
// Work-around for a bug fixed in PHP 5.5.10 https://bugs.php.net/bug.php?id=45528
// See: https://stackoverflow.com/q/14068594/2646927
// @codeCoverageIgnoreStart
if (strpos($object, ':') !== false) {
try {
return static::createFromFormat('O', $object)->getTimezone();
} catch (InvalidArgumentException $e) {
//
}
}
// @codeCoverageIgnoreEnd
throw new InvalidArgumentException('Unknown or bad timezone ('.$object.')');
}
///////////////////////////////////////////////////////////////////
//////////////////////////// CONSTRUCTORS /////////////////////////
///////////////////////////////////////////////////////////////////
/**
* Create a new Carbon instance.
*
* Please see the testing aids section (specifically static::setTestNow())
* for more on the possibility of this constructor returning a test instance.
*
* @param string|null $time
* @param \DateTimeZone|string|null $tz
*/
public function __construct($time = null, $tz = null)
{
// If the class has a test now set and we are trying to create a now()
// instance then override as required
$isNow = empty($time) || $time === 'now';
if (static::hasTestNow() && ($isNow || static::hasRelativeKeywords($time))) {
$testInstance = clone static::getTestNow();
//shift the time according to the given time zone
if ($tz !== null && $tz !== static::getTestNow()->getTimezone()) {
$testInstance->setTimezone($tz);
} else {
$tz = $testInstance->getTimezone();
}
if (static::hasRelativeKeywords($time)) {
$testInstance->modify($time);
}
$time = $testInstance->format(static::MOCK_DATETIME_FORMAT);
}
$timezone = static::safeCreateDateTimeZone($tz);
// @codeCoverageIgnoreStart
if ($isNow && !isset($testInstance) && static::isMicrosecondsFallbackEnabled() && (
version_compare(PHP_VERSION, '7.1.0-dev', '<')
||
version_compare(PHP_VERSION, '7.1.3-dev', '>=') && version_compare(PHP_VERSION, '7.1.4-dev', '<')
)
) {
// Get microseconds from microtime() if "now" asked and PHP < 7.1 and PHP 7.1.3 if fallback enabled.
list($microTime, $timeStamp) = explode(' ', microtime());
$dateTime = new DateTime('now', $timezone);
$dateTime->setTimestamp($timeStamp); // Use the timestamp returned by microtime as now can happen in the next second
$time = $dateTime->format(static::DEFAULT_TO_STRING_FORMAT).substr($microTime, 1, 7);
}
// @codeCoverageIgnoreEnd
// Work-around for PHP bug https://bugs.php.net/bug.php?id=67127
if (strpos((string) .1, '.') === false) {
$locale = setlocale(LC_NUMERIC, '0');
setlocale(LC_NUMERIC, 'C');
}
parent::__construct($time, $timezone);
if (isset($locale)) {
setlocale(LC_NUMERIC, $locale);
}
static::setLastErrors(parent::getLastErrors());
}
/**
* Create a Carbon instance from a DateTime one.
*
* @param \DateTime|\DateTimeInterface $date
*
* @return static
*/
public static function instance($date)
{
if ($date instanceof static) {
return clone $date;
}
static::expectDateTime($date);
return new static($date->format('Y-m-d H:i:s.u'), $date->getTimezone());
}
/**
* Create a carbon instance from a string.
*
* This is an alias for the constructor that allows better fluent syntax
* as it allows you to do Carbon::parse('Monday next week')->fn() rather
* than (new Carbon('Monday next week'))->fn().
*
* @param string|null $time
* @param \DateTimeZone|string|null $tz
*
* @return static
*/
public static function parse($time = null, $tz = null)
{
return new static($time, $tz);
}
/**
* Get a Carbon instance for the current date and time.
*
* @param \DateTimeZone|string|null $tz
*
* @return static
*/
public static function now($tz = null)
{
return new static(null, $tz);
}
/**
* Create a Carbon instance for today.
*
* @param \DateTimeZone|string|null $tz
*
* @return static
*/
public static function today($tz = null)
{
return static::parse('today', $tz);
}
/**
* Create a Carbon instance for tomorrow.
*
* @param \DateTimeZone|string|null $tz
*
* @return static
*/
public static function tomorrow($tz = null)
{
return static::parse('tomorrow', $tz);
}
/**
* Create a Carbon instance for yesterday.
*
* @param \DateTimeZone|string|null $tz
*
* @return static
*/
public static function yesterday($tz = null)
{
return static::parse('yesterday', $tz);
}
/**
* Create a Carbon instance for the greatest supported date.
*
* @return static
*/
public static function maxValue()
{
if (self::$PHPIntSize === 4) {
// 32 bit
return static::createFromTimestamp(PHP_INT_MAX); // @codeCoverageIgnore
}
// 64 bit
return static::create(9999, 12, 31, 23, 59, 59);
}
/**
* Create a Carbon instance for the lowest supported date.
*
* @return static
*/
public static function minValue()
{
if (self::$PHPIntSize === 4) {
// 32 bit
return static::createFromTimestamp(~PHP_INT_MAX); // @codeCoverageIgnore
}
// 64 bit
return static::create(1, 1, 1, 0, 0, 0);
}
/**
* Create a new Carbon instance from a specific date and time.
*
* If any of $year, $month or $day are set to null their now() values will
* be used.
*
* If $hour is null it will be set to its now() value and the default
* values for $minute and $second will be their now() values.
*
* If $hour is not null then the default values for $minute and $second
* will be 0.
*
* @param int|null $year
* @param int|null $month
* @param int|null $day
* @param int|null $hour
* @param int|null $minute
* @param int|null $second
* @param \DateTimeZone|string|null $tz
*
* @throws \InvalidArgumentException
*
* @return static
*/
public static function create($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null)
{
$now = static::hasTestNow() ? static::getTestNow() : static::now($tz);
$defaults = array_combine(array(
'year',
'month',
'day',
'hour',
'minute',
'second',
), explode('-', $now->format('Y-n-j-G-i-s')));
$year = $year === null ? $defaults['year'] : $year;
$month = $month === null ? $defaults['month'] : $month;
$day = $day === null ? $defaults['day'] : $day;
if ($hour === null) {
$hour = $defaults['hour'];
$minute = $minute === null ? $defaults['minute'] : $minute;
$second = $second === null ? $defaults['second'] : $second;
} else {
$minute = $minute === null ? 0 : $minute;
$second = $second === null ? 0 : $second;
}
$fixYear = null;
if ($year < 0) {
$fixYear = $year;
$year = 0;
} elseif ($year > 9999) {
$fixYear = $year - 9999;
$year = 9999;
}
$instance = static::createFromFormat('!Y-n-j G:i:s', sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $tz);
if ($fixYear !== null) {
$instance->addYears($fixYear);
}
return $instance;
}
/**
* Create a new safe Carbon instance from a specific date and time.
*
* If any of $year, $month or $day are set to null their now() values will
* be used.
*
* If $hour is null it will be set to its now() value and the default
* values for $minute and $second will be their now() values.
*
* If $hour is not null then the default values for $minute and $second
* will be 0.
*
* If one of the set values is not valid, an \InvalidArgumentException
* will be thrown.
*
* @param int|null $year
* @param int|null $month
* @param int|null $day
* @param int|null $hour
* @param int|null $minute
* @param int|null $second
* @param \DateTimeZone|string|null $tz
*
* @throws \Carbon\Exceptions\InvalidDateException|\InvalidArgumentException
*
* @return static
*/
public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null)
{
$fields = array(
'year' => array(0, 9999),
'month' => array(0, 12),
'day' => array(0, 31),
'hour' => array(0, 24),
'minute' => array(0, 59),
'second' => array(0, 59),
);
foreach ($fields as $field => $range) {
if ($$field !== null && (!is_int($$field) || $$field < $range[0] || $$field > $range[1])) {
throw new InvalidDateException($field, $$field);
}
}
$instance = static::create($year, $month, $day, $hour, $minute, $second, $tz);
foreach (array_reverse($fields) as $field => $range) {
if ($$field !== null && (!is_int($$field) || $$field !== $instance->$field)) {
throw new InvalidDateException($field, $$field);
}
}
return $instance;
}
/**
* Create a Carbon instance from just a date. The time portion is set to now.
*
* @param int|null $year
* @param int|null $month
* @param int|null $day
* @param \DateTimeZone|string|null $tz
*
* @throws \InvalidArgumentException
*
* @return static
*/
public static function createFromDate($year = null, $month = null, $day = null, $tz = null)
{
return static::create($year, $month, $day, null, null, null, $tz);
}
/**
* Create a Carbon instance from just a date. The time portion is set to midnight.
*
* @param int|null $year
* @param int|null $month
* @param int|null $day
* @param \DateTimeZone|string|null $tz
*
* @return static
*/
public static function createMidnightDate($year = null, $month = null, $day = null, $tz = null)
{
return static::create($year, $month, $day, 0, 0, 0, $tz);
}
/**
* Create a Carbon instance from just a time. The date portion is set to today.
*
* @param int|null $hour
* @param int|null $minute
* @param int|null $second
* @param \DateTimeZone|string|null $tz
*
* @throws \InvalidArgumentException
*
* @return static
*/
public static function createFromTime($hour = null, $minute = null, $second = null, $tz = null)
{
return static::create(null, null, null, $hour, $minute, $second, $tz);
}
/**
* Create a Carbon instance from a time string. The date portion is set to today.
*
* @param string $time
* @param \DateTimeZone|string|null $tz
*
* @throws \InvalidArgumentException
*
* @return static
*/
public static function createFromTimeString($time, $tz = null)
{
return static::today($tz)->setTimeFromTimeString($time);
}
private static function createFromFormatAndTimezone($format, $time, $tz)
{
return $tz !== null
? parent::createFromFormat($format, $time, static::safeCreateDateTimeZone($tz))
: parent::createFromFormat($format, $time);
}
/**
* Create a Carbon instance from a specific format.
*
* @param string $format Datetime format
* @param string $time
* @param \DateTimeZone|string|null $tz
*
* @throws InvalidArgumentException
*
* @return static
*/
public static function createFromFormat($format, $time, $tz = null)
{
// First attempt to create an instance, so that error messages are based on the unmodified format.
$date = self::createFromFormatAndTimezone($format, $time, $tz);
$lastErrors = parent::getLastErrors();
if (($mock = static::getTestNow()) && ($date instanceof DateTime || $date instanceof DateTimeInterface)) {
// Set timezone from mock if custom timezone was neither given directly nor as a part of format.
// First let's skip the part that will be ignored by the parser.
$nonEscaped = '(?<!\\\\)(\\\\{2})*';
$nonIgnored = preg_replace("/^.*{$nonEscaped}!/s", '', $format);
if ($tz === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) {
$tz = $mock->getTimezone();
}
// Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag.
if (!preg_match("/{$nonEscaped}[!|]/", $format)) {
$format = static::MOCK_DATETIME_FORMAT.' '.$format;
$time = $mock->format(static::MOCK_DATETIME_FORMAT).' '.$time;
}
// Regenerate date from the modified format to base result on the mocked instance instead of now.
$date = self::createFromFormatAndTimezone($format, $time, $tz);
}
if ($date instanceof DateTime || $date instanceof DateTimeInterface) {
$instance = static::instance($date);
$instance::setLastErrors($lastErrors);
return $instance;
}
throw new InvalidArgumentException(implode(PHP_EOL, $lastErrors['errors']));
}
/**
* Set last errors.
*
* @param array $lastErrors
*
* @return void
*/
private static function setLastErrors(array $lastErrors)
{
static::$lastErrors = $lastErrors;
}
/**
* {@inheritdoc}
*/
public static function getLastErrors()
{
return static::$lastErrors;
}
/**
* Create a Carbon instance from a timestamp.
*
* @param int $timestamp
* @param \DateTimeZone|string|null $tz
*
* @return static
*/
public static function createFromTimestamp($timestamp, $tz = null)
{
return static::today($tz)->setTimestamp($timestamp);
}
/**
* Create a Carbon instance from a timestamp in milliseconds.
*
* @param int $timestamp
* @param \DateTimeZone|string|null $tz
*
* @return static
*/
public static function createFromTimestampMs($timestamp, $tz = null)
{
return static::createFromFormat('U.u', sprintf('%F', $timestamp / 1000))
->setTimezone($tz);
}
/**
* Create a Carbon instance from an UTC timestamp.
*
* @param int $timestamp
*
* @return static
*/
public static function createFromTimestampUTC($timestamp)
{
return new static('@'.$timestamp);
}
/**
* Make a Carbon instance from given variable if possible.
*
* Always return a new instance. Parse only strings and only these likely to be dates (skip intervals
* and recurrences). Throw an exception for invalid format, but otherwise return null.
*
* @param mixed $var
*
* @return static|null
*/
public static function make($var)
{
if ($var instanceof DateTime || $var instanceof DateTimeInterface) {
return static::instance($var);
}
if (is_string($var)) {
$var = trim($var);
$first = substr($var, 0, 1);
if (is_string($var) && $first !== 'P' && $first !== 'R' && preg_match('/[a-z0-9]/i', $var)) {
return static::parse($var);
}
}
}
/**
* Get a copy of the instance.
*
* @return static