如何为时间戳设置 Laravel Carbon 时区?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37722681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:24:35  来源:igfitidea点击:

How to set Laravel Carbon timezone for timestamps?

laraveleloquentphp-carbon

提问by Yuray

I have a project which is primarily based in CET region. I set CET in config/app.php, but all pivot timestamps in the base are stored in UTC time?

我有一个主要位于 CET 地区的项目。我在 config/app.php 中设置了 CET,但基础中的所有枢轴时间戳都以 UTC 时间存储?

How can I set "global" timezone for timestamps?

如何为时间戳设置“全局”时区?

i made this test:

我做了这个测试:

<?php
$timezone = date_default_timezone_get();
echo "The current server timezone is: " . $timezone;
echo "<br />".date('m/d/Y h:i:s a', time());

$mytime = Carbon\Carbon::now();
echo "<br />".$mytime->toDateTimeString();
?>

and here's the result:

结果如下:

The current server timezone is: CET
06/09/2016 12:06:04 pm
2016-06-09 11:06:04

tnx Y

tnx y

回答by thefallen

Carbon uses the default DateTimePHP object, so use the date_default_timezone_set()function, for example: date_default_timezone_set('Europe/London');

Carbon 使用默认的DateTimePHP 对象,因此使用date_default_timezone_set()函数,例如: date_default_timezone_set('Europe/London');

回答by Hisham Shami

in the AppServiceProvider.php you can add the php functionality to alter the timestamp for the whole project

在 AppServiceProvider.php 中,您可以添加 php 功能来更改整个项目的时间戳

public function boot()
{
    Schema::defaultStringLength(191);
    date_default_timezone_set('Asia/Aden');
}

回答by Adam Pery

Update file config/app.php

更新文件 config/app.php

Eg: 'timezone' => 'Asia/Jerusalem'instead of 'timezone' => 'UTC'

例如:'timezone' => 'Asia/Jerusalem'代替'timezone' => 'UTC'

回答by GONG

You can achieve it with mutators

你可以用mutators来实现

public function getCreatedAtAttribute($value)
{

return Carbon::createFromTimestamp(strtotime($value))
    ->timezone(Config::get('app.timezone'))
    ->toDateTimeString(); //remove this one if u want to return Carbon object
}

回答by Ashwani Garg

If you are using Laravel Carbon TimeStamps, then you have to change timezone in App/Providers/AppServiceProvider.php file

如果您使用的是 Laravel Carbon TimeStamps,则必须在 App/Providers/AppServiceProvider.php 文件中更改时区

// App/Providers/AppServiceProvider.php

// App/Providers/AppServiceProvider.php

public function boot()
{
    date_default_timezone_set('Asia/Calcutta');
}

回答by Yuray

It looks like solution is to use not "CET" but one of explicit timezones, for example: "Europe\Minsk"

看起来解决方案不是使用“CET”而是使用明确的时区之一,例如:“Europe\Minsk”

PHP Timezones

PHP 时区

Timezones in Laravel 4

Laravel 4 中的时区