-2

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?

POV
  • 11,293
  • 34
  • 107
  • 201
  • 1
    your looping an empty array –  Aug 08 '19 at 22:33
  • So you are setting `$response` to an empty array and then looping over it? – ehymel Aug 08 '19 at 22:33
  • What function is throwing the _Unexpected data found_ error? It looks like you've got a trace right there. – Halcyon Aug 08 '19 at 22:38
  • the response `array` is empty. BTW, using `gmdate("d/m/Y H:i", strtotime($v->created_at))` would give you the `UTC` time directly, see [gmdate](https://www.php.net/manual/fr/function.gmdate.php) on `php.net` docs. – ThS Aug 08 '19 at 22:40
  • Array is filled, I just shorted it – POV Aug 08 '19 at 22:46

1 Answers1

1

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
}
Ezequiel Fernandez
  • 954
  • 11
  • 18