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:
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
Maybe my $timestamp
is empty somewhere?
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
}