Laravel Carbon 如何在不改变小时的情况下改变时区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45870577/
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-14 16:32:59  来源:igfitidea点击:

Laravel Carbon how to change timezone without changing the hour

phplaraveldatetimelaravel-5

提问by Eric Brown

I am trying to find a workaround for how I can convert the datetime stored in my Database as 'yyyy-mm-dd HH-mm-ss' and give it the timezone 'America/Los_Angeles'.

我正在尝试找到一种解决方法,如何将存储在我的数据库中的日期时间转换为“yyyy-mm-dd HH-mm-ss”,并为其指定时区“America/Los_Angeles”。

If I change the timezone, Carbon will automatically subtract 7 hours from the time, which is what happens when changing the time from UTC to PST, but the time in my DB is set for PST time. For example, I want the time to be 10am today, but it I change the timezone, Carbon will convert it to 3am today.

如果我更改时区,Carbon 将自动从时间中减去 7 小时,这是将时间从 UTC 更改为 PST 时发生的情况,但我的数据库中的时间设置为 PST 时间。例如,我希望今天的时间是上午 10 点,但是我更改了时区,Carbon 会将其转换为今天上午 3 点。

How can I make it where the timezone gets changed to PST but still keep the time at 10am? I need the timezone for an API call, which is why I need this figured out.

如何将时区更改为 PST 但仍将时间保持在上午 10 点?我需要 API 调用的时区,这就是我需要弄清楚的原因。

采纳答案by Eric Brown

Ok, I figured out a dumb, but functional way of doing what I wanted to do, and it works.

好吧,我想出了一种愚蠢但实用的方法来做我想做的事情,并且它有效。

Here is my code:

这是我的代码:

      $dt = Carbon::parse($request->ShootDateTime)->timezone('America/Los_Angeles');
      $toDay = $dt->format('d');
      $toMonth = $dt->format('m');
      $toYear = $dt->format('Y');
      $dateUTC = Carbon::createFromDate($toYear, $toMonth, $toDay, 'UTC');
      $datePST = Carbon::createFromDate($toYear, $toMonth, $toDay, 'America/Los_Angeles');
      $difference = $dateUTC->diffInHours($datePST);
      $date = $dt->addHours($difference);

I get the time I wanted to convert to a timezone and parse it and change the timezone. I then get the Day, Month, and Year and create 2 different Dates, both will read as being 00:00:00 in time, but because they are separate by 7 hours in this instance, they can only both be 00:00:00 if they are 7 hours different, which is what I capture next. Then finally, I take the initial datetime and add the difference to it, giving me the proper time in the proper timezone.

我有时间想转换为时区并解析它并更改时区。然后我获取日、月和年并创建 2 个不同的日期,两者在时间上都将读取为 00:00:00,但由于在这种情况下它们相隔 7 小时,因此它们只能是 00:00: 00 如果它们有 7 个小时的不同,这就是我接下来要捕获的内容。最后,我取初始日期时间并将差异添加到它,在适当的时区给我适当的时间。

It's ugly, but it works.

这很丑陋,但它有效。

回答by Abhishek Sachan

A better and simpler way would be:

更好更简单的方法是:

$carbon = new Carbon('YYYY-MM-DD HH:II:SS', 'America/Los_Angeles');

NOTE: Don't forget to add dependency use \Carbon\Carbon;.

注意:不要忘记添加依赖项use \Carbon\Carbon;

回答by AfikDeri

I think that what you'r looking for is this:

我认为你要找的是这个:

Carbon::createFromFormat('Y-m-d H:i:s', $some_date, 'UTC')
    ->setTimezone('America/Los_Angeles')

First, you set the timezone you initially have, so if you store your date in the database as UTC, then set the default timezone to UTC, then use ->setTimeZone('Valid/Timezone')to make the change from what you'v had to the new timezone.

首先,您设置最初拥有的时区,因此,如果您在数据库中将日期存储为 UTC,则将默认时区设置为 UTC,然后用于->setTimeZone('Valid/Timezone')将您拥有的时区更改为新时区。

回答by Alex Ciocan

/**
 * Return the formated date based on timezone selected from sidebar nav | Front-end user | Saved in Cookie | Sent $to
 *
 * @param Carbon $date
 * @param null $type (long | short)
 * @return Carbon date
 */
public static function formatDateTimeZone($date, $type = 'long', $from = null, $to = null)
{
    if (!$from)
        $from = 'UTC';

    if (!$to)
        $to = Cookie::get('timezone_user');

    $dateUTC = Carbon::now();
    $datePST = Carbon::now();
    $datePST->setTimezone($to);

    $start  = new Carbon($dateUTC);
    $end    = new Carbon($datePST);
    $difference = $start->diffInHours($end, false); // set false to see the negative difference

    $carbon = Carbon::createFromFormat('Y-m-d H:i:s', $date, $from); // specify UTC otherwise defaults to locale time zone as per ini setting
    $carbon->addHours($difference);

    if ($type == 'short')
    {
        $carbon = Carbon::parse($carbon)->format('Y-m-d');
    }

    return $carbon;
}

call: $date = Date::formatDateTimeZone(Carbon::parse('2019-11-01 06:00:00'), 'long', 'UTC', 'America/Los_Angeles');

称呼: $date = Date::formatDateTimeZone(Carbon::parse('2019-11-01 06:00:00'), 'long', 'UTC', 'America/Los_Angeles');

I've created this function to format the dates saved in Database as UTC and show it correctly to chart.

我创建了这个函数来将保存在数据库中的日期格式化为 UTC 并将其正确显示到图表中。

It makes the difference of actual timezone hours and applies the same logic for old dates. (e.g. 2019-11-04 where the difference is -7h)

它使实际时区小时数有所不同,并对旧日期应用相同的逻辑。(例如 2019-11-04,其中差异为 -7h)

Laravel 5.8

Laravel 5.8