-
Notifications
You must be signed in to change notification settings - Fork 105
/
DateTimeFormatter.php
108 lines (90 loc) · 3.09 KB
/
DateTimeFormatter.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
<?php
namespace Knp\Bundle\TimeBundle;
use Symfony\Contracts\Translation\TranslatorInterface;
final class DateTimeFormatter
{
/**
* @internal
*/
public function __construct(private TranslatorInterface $translator)
{
}
/**
* Returns a formatted diff for the given from and to datetimes.
*/
public function formatDiff(
int|string|\DateTimeInterface $from,
int|string|\DateTimeInterface $to = null,
string $locale = null
): string {
$from = self::formatDateTime($from);
$to = self::formatDateTime($to);
static $units = [
'y' => 'year',
'm' => 'month',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
];
$diff = $to->diff($from);
foreach ($units as $attribute => $unit) {
$count = $diff->$attribute;
if (0 !== $count) {
$id = sprintf('diff.%s.%s', $diff->invert ? 'ago' : 'in', $unit);
return $this->translator->trans($id, ['%count%' => $count], 'time', $locale);
}
}
return $this->translator->trans('diff.empty', [], 'time', $locale);
}
/**
* @author Fabien Potencier <[email protected]>
*
* @source https://github.com/symfony/symfony/blob/ad72245261792c6b5d2db821fcbd141b11095215/src/Symfony/Component/Console/Helper/Helper.php#L97
*/
public function formatDuration(float $seconds, string $locale = null): string
{
static $timeFormats = [
[0, 'duration.none'],
[1, 'duration.second'],
[2, 'duration.second', 1],
[60, 'duration.minute'],
[120, 'duration.minute', 60],
[3600, 'duration.hour'],
[7200, 'duration.hour', 3600],
[86400, 'duration.day'],
[172800, 'duration.day', 86400],
];
foreach ($timeFormats as $index => $format) {
if ($seconds >= $format[0]) {
if ((isset($timeFormats[$index + 1]) && $seconds < $timeFormats[$index + 1][0])
|| $index === \count($timeFormats) - 1
) {
if (2 === \count($format)) {
return $this->translator->trans($format[1], [], 'time', $locale);
}
return $this->translator->trans(
$format[1],
['%count%' => floor($seconds / $format[2])],
'time',
$locale
);
}
}
}
return $this->translator->trans('duration.none', [], 'time', $locale);
}
private static function formatDateTime(int|string|\DateTimeInterface|null $value): \DateTimeInterface
{
if ($value instanceof \DateTimeInterface) {
return $value;
}
if (is_int($value)) {
$value = date('Y-m-d H:i:s', $value);
}
if (null === $value) {
$value = 'now';
}
return new \DateTime($value);
}
}