|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace JamesMills\LaravelTimezone; |
|
4
|
|
|
|
|
5
|
|
|
use Carbon\Carbon; |
|
6
|
|
|
|
|
7
|
|
|
class Timezone |
|
8
|
|
|
{ |
|
9
|
|
|
/** |
|
10
|
|
|
* @param Carbon|null $date |
|
11
|
|
|
* @param null $format |
|
|
|
|
|
|
12
|
|
|
* @param bool $format_timezone |
|
13
|
|
|
* @return string |
|
14
|
|
|
*/ |
|
15
|
|
|
public function convertToLocal(?Carbon $date, $format = null, $format_timezone = false, $diff_for_humans = false): string |
|
16
|
|
|
{ |
|
17
|
|
|
if (is_null($date)) { |
|
18
|
|
|
return 'Empty'; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
$timezone = (auth()->user()->timezone) ?? config('app.timezone'); |
|
22
|
|
|
|
|
23
|
|
|
$date->setTimezone($timezone); |
|
24
|
|
|
|
|
25
|
|
|
if (is_null($format)) { |
|
|
|
|
|
|
26
|
|
|
return $date->format(config('timezone.format')); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
if ($diff_for_humans) { |
|
30
|
|
|
return $date->diffForHumans(); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
$formatted_date_time = $date->format($format); |
|
34
|
|
|
|
|
35
|
|
|
if ($format_timezone) { |
|
36
|
|
|
return $formatted_date_time . ' ' . $this->formatTimezone($date); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
return $formatted_date_time; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @param Carbon|null $date |
|
44
|
|
|
* @return string |
|
45
|
|
|
*/ |
|
46
|
|
|
public function convertToLocalDiffForHumans(?Carbon $date): string |
|
47
|
|
|
{ |
|
48
|
|
|
return $this->convertToLocal($date, null, false, true); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @param $date |
|
53
|
|
|
* @return Carbon |
|
54
|
|
|
*/ |
|
55
|
|
|
public function convertFromLocal($date): Carbon |
|
56
|
|
|
{ |
|
57
|
|
|
return Carbon::parse($date, auth()->user()->timezone)->setTimezone('UTC'); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* @param Carbon $date |
|
62
|
|
|
* @return string |
|
63
|
|
|
*/ |
|
64
|
|
|
private function formatTimezone(Carbon $date): string |
|
65
|
|
|
{ |
|
66
|
|
|
$timezone = $date->format('e'); |
|
67
|
|
|
$parts = explode('/', $timezone); |
|
68
|
|
|
|
|
69
|
|
|
if (count($parts) > 1) { |
|
70
|
|
|
return str_replace('_', ' ', $parts[1]) . ', ' . $parts[0]; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
return str_replace('_', ' ', $parts[0]); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|