forked from jamesmills/laravel-timezone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTimezone.php
64 lines (50 loc) · 1.71 KB
/
Timezone.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
<?php
namespace JamesMills\LaravelTimezone;
use Carbon\Carbon;
class Timezone
{
/**
* @param Carbon\Carbon|null $date
* @param null $format
* @param bool $format_timezone
* @return string
*/
public function convertToLocal(?Carbon $date, $format = null, $format_timezone = false, $enableTranslation = null) : string
{
if (is_null($date)) {
return __('Empty');
}
$timezone = (auth()->user()->timezone) ?? config('app.timezone');
$enableTranslation = $enableTranslation !== null ? $enableTranslation : config('timezone.enableTranslation');
$date->setTimezone($timezone);
if (is_null($format)) {
return $enableTranslation ? $date->translatedFormat(config('timezone.format')) : $date->format(config('timezone.format'));
}
$formatted_date_time = $enableTranslation ? $date->translatedFormat($format) : $date->format($format);
if ($format_timezone) {
return $formatted_date_time . ' ' . $this->formatTimezone($date);
}
return $formatted_date_time;
}
/**
* @param $date
* @return Carbon\Carbon
*/
public function convertFromLocal($date) : Carbon
{
return Carbon::parse($date, auth()->user()->timezone)->setTimezone('UTC');
}
/**
* @param Carbon\Carbon $date
* @return string
*/
private function formatTimezone(Carbon $date) : string
{
$timezone = $date->format('e');
$parts = explode('/', $timezone);
if (count($parts) > 1) {
return str_replace('_', ' ', $parts[1]) . ', ' . $parts[0];
}
return str_replace('_', ' ', $parts[0]);
}
}