1
<?php
2

3
/**
4
 * This file is part of the Carbon package.
5
 *
6
 * (c) Brian Nesbitt <brian@nesbot.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
namespace Carbon\Traits;
12

13
use Carbon\Carbon;
14
use Carbon\CarbonImmutable;
15
use Carbon\CarbonInterface;
16
use Carbon\CarbonInterval;
17
use Carbon\CarbonPeriod;
18
use Carbon\Exceptions\UnitException;
19
use Closure;
20
use DateTime;
21
use DateTimeImmutable;
22

23
/**
24
 * Trait Converter.
25
 *
26
 * Change date into different string formats and types and
27
 * handle the string cast.
28
 *
29
 * Depends on the following methods:
30
 *
31
 * @method static copy()
32
 */
33
trait Converter
34
{
35
    /**
36
     * Format to use for __toString method when type juggling occurs.
37
     *
38
     * @var string|Closure|null
39
     */
40
    protected static $toStringFormat = null;
41

42
    /**
43
     * Reset the format used to the default when type juggling a Carbon instance to a string
44
     *
45
     * @return void
46
     */
47 1
    public static function resetToStringFormat()
48
    {
49 1
        static::setToStringFormat(null);
50
    }
51

52
    /**
53
     * @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
54
     *             You should rather let Carbon object being casted to string with DEFAULT_TO_STRING_FORMAT, and
55
     *             use other method or custom format passed to format() method if you need to dump an other string
56
     *             format.
57
     *
58
     * Set the default format used when type juggling a Carbon instance to a string
59
     *
60
     * @param string|Closure|null $format
61
     *
62
     * @return void
63
     */
64 1
    public static function setToStringFormat($format)
65
    {
66 1
        static::$toStringFormat = $format;
67
    }
68

69
    /**
70
     * Returns the formatted date string on success or FALSE on failure.
71
     *
72
     * @see https://php.net/manual/en/datetime.format.php
73
     *
74
     * @param string $format
75
     *
76
     * @return string
77
     */
78 1
    public function format($format)
79
    {
80 1
        $function = $this->localFormatFunction ?: static::$formatFunction;
81

82 1
        if (!$function) {
83 1
            return $this->rawFormat($format);
84
        }
85

86 1
        if (\is_string($function) && method_exists($this, $function)) {
87 1
            $function = [$this, $function];
88
        }
89

90 1
        return $function(...\func_get_args());
91
    }
92

93
    /**
94
     * @see https://php.net/manual/en/datetime.format.php
95
     *
96
     * @param string $format
97
     *
98
     * @return string
99
     */
100 1
    public function rawFormat($format)
101
    {
102 1
        return parent::format($format);
103
    }
104

105
    /**
106
     * Format the instance as a string using the set format
107
     *
108
     * @example
109
     * ```
110
     * echo Carbon::now(); // Carbon instances can be casted to string
111
     * ```
112
     *
113
     * @return string
114
     */
115 1
    public function __toString()
116
    {
117 1
        $format = $this->localToStringFormat ?? static::$toStringFormat;
118

119 1
        return $format instanceof Closure
120 1
            ? $format($this)
121 1
            : $this->rawFormat($format ?: (
122 1
                \defined('static::DEFAULT_TO_STRING_FORMAT')
123 1
                    ? static::DEFAULT_TO_STRING_FORMAT
124 1
                    : CarbonInterface::DEFAULT_TO_STRING_FORMAT
125
            ));
126
    }
127

128
    /**
129
     * Format the instance as date
130
     *
131
     * @example
132
     * ```
133
     * echo Carbon::now()->toDateString();
134
     * ```
135
     *
136
     * @return string
137
     */
138 1
    public function toDateString()
139
    {
140 1
        return $this->rawFormat('Y-m-d');
141
    }
142

143
    /**
144
     * Format the instance as a readable date
145
     *
146
     * @example
147
     * ```
148
     * echo Carbon::now()->toFormattedDateString();
149
     * ```
150
     *
151
     * @return string
152
     */
153 1
    public function toFormattedDateString()
154
    {
155 1
        return $this->rawFormat('M j, Y');
156
    }
157

158
    /**
159
     * Format the instance as time
160
     *
161
     * @example
162
     * ```
163
     * echo Carbon::now()->toTimeString();
164
     * ```
165
     *
166
     * @param string $unitPrecision
167
     *
168
     * @return string
169
     */
170 1
    public function toTimeString($unitPrecision = 'second')
171
    {
172 1
        return $this->rawFormat(static::getTimeFormatByPrecision($unitPrecision));
173
    }
174

175
    /**
176
     * Format the instance as date and time
177
     *
178
     * @example
179
     * ```
180
     * echo Carbon::now()->toDateTimeString();
181
     * ```
182
     *
183
     * @param string $unitPrecision
184
     *
185
     * @return string
186
     */
187 1
    public function toDateTimeString($unitPrecision = 'second')
188
    {
189 1
        return $this->rawFormat('Y-m-d '.static::getTimeFormatByPrecision($unitPrecision));
190
    }
191

192
    /**
193
     * Return a format from H:i to H:i:s.u according to given unit precision.
194
     *
195
     * @param string $unitPrecision "minute", "second", "millisecond" or "microsecond"
196
     *
197
     * @return string
198
     */
199 1
    public static function getTimeFormatByPrecision($unitPrecision)
200
    {
201 1
        switch (static::singularUnit($unitPrecision)) {
202 1
            case 'minute':
203 1
                return 'H:i';
204 1
            case 'second':
205 1
                return 'H:i:s';
206 1
            case 'm':
207 1
            case 'millisecond':
208 1
                return 'H:i:s.v';
209 1
            case 'µ':
210 1
            case 'microsecond':
211 1
                return 'H:i:s.u';
212
        }
213

214 1
        throw new UnitException('Precision unit expected among: minute, second, millisecond and microsecond.');
215
    }
216

217
    /**
218
     * Format the instance as date and time T-separated with no timezone
219
     *
220
     * @example
221
     * ```
222
     * echo Carbon::now()->toDateTimeLocalString();
223
     * echo "\n";
224
     * echo Carbon::now()->toDateTimeLocalString('minute'); // You can specify precision among: minute, second, millisecond and microsecond
225
     * ```
226
     *
227
     * @param string $unitPrecision
228
     *
229
     * @return string
230
     */
231 1
    public function toDateTimeLocalString($unitPrecision = 'second')
232
    {
233 1
        return $this->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision));
234
    }
235

236
    /**
237
     * Format the instance with day, date and time
238
     *
239
     * @example
240
     * ```
241
     * echo Carbon::now()->toDayDateTimeString();
242
     * ```
243
     *
244
     * @return string
245
     */
246 1
    public function toDayDateTimeString()
247
    {
248 1
        return $this->rawFormat('D, M j, Y g:i A');
249
    }
250

251
    /**
252
     * Format the instance as ATOM
253
     *
254
     * @example
255
     * ```
256
     * echo Carbon::now()->toAtomString();
257
     * ```
258
     *
259
     * @return string
260
     */
261 1
    public function toAtomString()
262
    {
263 1
        return $this->rawFormat(DateTime::ATOM);
264
    }
265

266
    /**
267
     * Format the instance as COOKIE
268
     *
269
     * @example
270
     * ```
271
     * echo Carbon::now()->toCookieString();
272
     * ```
273
     *
274
     * @return string
275
     */
276 1
    public function toCookieString()
277
    {
278 1
        return $this->rawFormat(DateTime::COOKIE);
279
    }
280

281
    /**
282
     * Format the instance as ISO8601
283
     *
284
     * @example
285
     * ```
286
     * echo Carbon::now()->toIso8601String();
287
     * ```
288
     *
289
     * @return string
290
     */
291 1
    public function toIso8601String()
292
    {
293 1
        return $this->toAtomString();
294
    }
295

296
    /**
297
     * Format the instance as RFC822
298
     *
299
     * @example
300
     * ```
301
     * echo Carbon::now()->toRfc822String();
302
     * ```
303
     *
304
     * @return string
305
     */
306 1
    public function toRfc822String()
307
    {
308 1
        return $this->rawFormat(DateTime::RFC822);
309
    }
310

311
    /**
312
     * Convert the instance to UTC and return as Zulu ISO8601
313
     *
314
     * @example
315
     * ```
316
     * echo Carbon::now()->toIso8601ZuluString();
317
     * ```
318
     *
319
     * @param string $unitPrecision
320
     *
321
     * @return string
322
     */
323 1
    public function toIso8601ZuluString($unitPrecision = 'second')
324
    {
325 1
        return $this->copy()->utc()->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision).'\Z');
326
    }
327

328
    /**
329
     * Format the instance as RFC850
330
     *
331
     * @example
332
     * ```
333
     * echo Carbon::now()->toRfc850String();
334
     * ```
335
     *
336
     * @return string
337
     */
338 1
    public function toRfc850String()
339
    {
340 1
        return $this->rawFormat(DateTime::RFC850);
341
    }
342

343
    /**
344
     * Format the instance as RFC1036
345
     *
346
     * @example
347
     * ```
348
     * echo Carbon::now()->toRfc1036String();
349
     * ```
350
     *
351
     * @return string
352
     */
353 1
    public function toRfc1036String()
354
    {
355 1
        return $this->rawFormat(DateTime::RFC1036);
356
    }
357

358
    /**
359
     * Format the instance as RFC1123
360
     *
361
     * @example
362
     * ```
363
     * echo Carbon::now()->toRfc1123String();
364
     * ```
365
     *
366
     * @return string
367
     */
368 1
    public function toRfc1123String()
369
    {
370 1
        return $this->rawFormat(DateTime::RFC1123);
371
    }
372

373
    /**
374
     * Format the instance as RFC2822
375
     *
376
     * @example
377
     * ```
378
     * echo Carbon::now()->toRfc2822String();
379
     * ```
380
     *
381
     * @return string
382
     */
383 1
    public function toRfc2822String()
384
    {
385 1
        return $this->rawFormat(DateTime::RFC2822);
386
    }
387

388
    /**
389
     * Format the instance as RFC3339
390
     *
391
     * @param bool $extended
392
     *
393
     * @example
394
     * ```
395
     * echo Carbon::now()->toRfc3339String() . "\n";
396
     * echo Carbon::now()->toRfc3339String(true) . "\n";
397
     * ```
398
     *
399
     * @return string
400
     */
401 1
    public function toRfc3339String($extended = false)
402
    {
403 1
        $format = DateTime::RFC3339;
404 1
        if ($extended) {
405 1
            $format = DateTime::RFC3339_EXTENDED;
406
        }
407

408 1
        return $this->rawFormat($format);
409
    }
410

411
    /**
412
     * Format the instance as RSS
413
     *
414
     * @example
415
     * ```
416
     * echo Carbon::now()->toRssString();
417
     * ```
418
     *
419
     * @return string
420
     */
421 1
    public function toRssString()
422
    {
423 1
        return $this->rawFormat(DateTime::RSS);
424
    }
425

426
    /**
427
     * Format the instance as W3C
428
     *
429
     * @example
430
     * ```
431
     * echo Carbon::now()->toW3cString();
432
     * ```
433
     *
434
     * @return string
435
     */
436 1
    public function toW3cString()
437
    {
438 1
        return $this->rawFormat(DateTime::W3C);
439
    }
440

441
    /**
442
     * Format the instance as RFC7231
443
     *
444
     * @example
445
     * ```
446
     * echo Carbon::now()->toRfc7231String();
447
     * ```
448
     *
449
     * @return string
450
     */
451 1
    public function toRfc7231String()
452
    {
453 1
        return $this->copy()
454 1
            ->setTimezone('GMT')
455 1
            ->rawFormat(\defined('static::RFC7231_FORMAT') ? static::RFC7231_FORMAT : CarbonInterface::RFC7231_FORMAT);
456
    }
457

458
    /**
459
     * Get default array representation.
460
     *
461
     * @example
462
     * ```
463
     * var_dump(Carbon::now()->toArray());
464
     * ```
465
     *
466
     * @return array
467
     */
468 1
    public function toArray()
469
    {
470
        return [
471 1
            'year' => $this->year,
472 1
            'month' => $this->month,
473 1
            'day' => $this->day,
474 1
            'dayOfWeek' => $this->dayOfWeek,
475 1
            'dayOfYear' => $this->dayOfYear,
476 1
            'hour' => $this->hour,
477 1
            'minute' => $this->minute,
478 1
            'second' => $this->second,
479 1
            'micro' => $this->micro,
480 1
            'timestamp' => $this->timestamp,
481 1
            'formatted' => $this->rawFormat(\defined('static::DEFAULT_TO_STRING_FORMAT') ? static::DEFAULT_TO_STRING_FORMAT : CarbonInterface::DEFAULT_TO_STRING_FORMAT),
482 1
            'timezone' => $this->timezone,
483
        ];
484
    }
485

486
    /**
487
     * Get default object representation.
488
     *
489
     * @example
490
     * ```
491
     * var_dump(Carbon::now()->toObject());
492
     * ```
493
     *
494
     * @return object
495
     */
496 1
    public function toObject()
497
    {
498 1
        return (object) $this->toArray();
499
    }
500

501
    /**
502
     * Returns english human readable complete date string.
503
     *
504
     * @example
505
     * ```
506
     * echo Carbon::now()->toString();
507
     * ```
508
     *
509
     * @return string
510
     */
511 1
    public function toString()
512
    {
513 1
        return $this->copy()->locale('en')->isoFormat('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
514
    }
515

516
    /**
517
     * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z, if $keepOffset truthy, offset will be kept:
518
     * 1977-04-22T01:00:00-05:00).
519
     *
520
     * @example
521
     * ```
522
     * echo Carbon::now('America/Toronto')->toISOString() . "\n";
523
     * echo Carbon::now('America/Toronto')->toISOString(true) . "\n";
524
     * ```
525
     *
526
     * @param bool $keepOffset Pass true to keep the date offset. Else forced to UTC.
527
     *
528
     * @return null|string
529
     */
530 1
    public function toISOString($keepOffset = false)
531
    {
532 1
        if (!$this->isValid()) {
533 1
            return null;
534
        }
535

536 1
        $yearFormat = $this->year < 0 || $this->year > 9999 ? 'YYYYYY' : 'YYYY';
537 1
        $tzFormat = $keepOffset ? 'Z' : '[Z]';
538 1
        $date = $keepOffset ? $this : $this->copy()->utc();
539

540 1
        return $date->isoFormat("$yearFormat-MM-DD[T]HH:mm:ss.SSSSSS$tzFormat");
541
    }
542

543
    /**
544
     * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z) with UTC timezone.
545
     *
546
     * @example
547
     * ```
548
     * echo Carbon::now('America/Toronto')->toJSON();
549
     * ```
550
     *
551
     * @return null|string
552
     */
553 1
    public function toJSON()
554
    {
555 1
        return $this->toISOString();
556
    }
557

558
    /**
559
     * Return native DateTime PHP object matching the current instance.
560
     *
561
     * @example
562
     * ```
563
     * var_dump(Carbon::now()->toDateTime());
564
     * ```
565
     *
566
     * @return DateTime
567
     */
568 1
    public function toDateTime()
569
    {
570 1
        return new DateTime($this->rawFormat('Y-m-d H:i:s.u'), $this->getTimezone());
571
    }
572

573
    /**
574
     * Return native toDateTimeImmutable PHP object matching the current instance.
575
     *
576
     * @example
577
     * ```
578
     * var_dump(Carbon::now()->toDateTimeImmutable());
579
     * ```
580
     *
581
     * @return DateTimeImmutable
582
     */
583 1
    public function toDateTimeImmutable()
584
    {
585 1
        return new DateTimeImmutable($this->rawFormat('Y-m-d H:i:s.u'), $this->getTimezone());
586
    }
587

588
    /**
589
     * @alias toDateTime
590
     *
591
     * Return native DateTime PHP object matching the current instance.
592
     *
593
     * @example
594
     * ```
595
     * var_dump(Carbon::now()->toDate());
596
     * ```
597
     *
598
     * @return DateTime
599
     */
600 1
    public function toDate()
601
    {
602 1
        return $this->toDateTime();
603
    }
604

605
    /**
606
     * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval).
607
     *
608
     * @param \DateTimeInterface|Carbon|CarbonImmutable|int|null $end      period end date or recurrences count if int
609
     * @param int|\DateInterval|string|null                      $interval period default interval or number of the given $unit
610
     * @param string|null                                        $unit     if specified, $interval must be an integer
611
     *
612
     * @return CarbonPeriod
613
     */
614 1
    public function toPeriod($end = null, $interval = null, $unit = null)
615
    {
616 1
        if ($unit) {
617 1
            $interval = CarbonInterval::make("$interval ".static::pluralUnit($unit));
618
        }
619

620 1
        $period = (new CarbonPeriod())->setDateClass(static::class)->setStartDate($this);
621

622 1
        if ($interval) {
623 1
            $period->setDateInterval($interval);
624
        }
625

626 1
        if (\is_int($end) || \is_string($end) && ctype_digit($end)) {
627 1
            $period->setRecurrences($end);
628 1
        } elseif ($end) {
629 1
            $period->setEndDate($end);
630
        }
631

632 1
        return $period;
633
    }
634

635
    /**
636
     * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval).
637
     *
638
     * @param \DateTimeInterface|Carbon|CarbonImmutable|null $end      period end date
639
     * @param int|\DateInterval|string|null                  $interval period default interval or number of the given $unit
640
     * @param string|null                                    $unit     if specified, $interval must be an integer
641
     *
642
     * @return CarbonPeriod
643
     */
644 1
    public function range($end = null, $interval = null, $unit = null)
645
    {
646 1
        return $this->toPeriod($end, $interval, $unit);
647
    }
648
}

Read our documentation on viewing source code .

Loading