duan33360 2019-08-08 22:27
浏览 15
已采纳

意外数据发现日期格式?

There istimestamp field (not null) in UTC in database with value: 2019-08-09 20:06:08.

I tried to convert this time to local time using function:

private function toLocalTime($dateInUTC) {
        $time = strtotime($dateInUTC.' UTC');
        return date("d/m/Y H:i", $time);
}

Converting is:

$response = []; // Data is present here
foreach($response as $v) {
   $v->created_at = $this->toLocalTime($v->created_at);
}

On line where I call $this->toLocalTime() I get exception:

enter image description here

I have tried this code:

$timestamp = '2019-08-09 10:41:00';
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'UTC');
$date->setTimezone('your/timezone'); // 
$new_date = $date->format('your new format'); // Y-m-d H:i:s

enter image description here

Maybe my $timestamp is empty somewhere?

  • 写回答

1条回答 默认 最新

  • dtj88302 2019-08-08 22:40
    关注

    As I can see you have Carbon in your project:

    $timestamp = '2019-08-09 10:41:00';
    $date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'UTC');
    
    $date->setTimezone('America/Argentina/Buenos_Aires'); // or your timezone
    $new_date = $date->format('Y-m-d H:i:s'); // or your new format
    

    in your example:

    private function toLocalTime($dateInUTC) 
    {
        // parse your date with carbon and set that as UTC
        $date = Carbon::createFromFormat('Y-m-d H:i:s', $dateInUTC, 'UTC');
        // set your timezone to get a local time.
        $date->setTimezone('America/Argentina/Buenos_Aires'); // or your timezone
        return = $date->format('Y-m-d H:i:s'); // or your new format
    }
    

    https://www.php.net/manual/en/timezones.php

    If you don't have Carbon installed as your example using native php:

    private function toLocalTime($dateInUTC) 
    {
    
        $utc_date = \DateTime::createFromFormat('Y-m-d H:i:s', $dateInUTC), new DateTimeZone('UTC'));
    
        $utc_date->setTimeZone(new \DateTimeZone('America/Argentina/Buenos_Aires'); // or your timezone
    
        return $utc_date->format('Y-m-d H:i:s'); // or your new format
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理