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 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献