1

How to convert datetime with timezone to datetime. I have tried multiple which are available on PHP blog. But nothing worked out. I am retriving datetime from MySql query as 2017-01-20T13:59:19+03:00 format. But it shows the time zone separately as +03:00. Actually the correct time is 2017-01-20 16:59:19. So how can I show the correct time with adding GMT time in the datetime stamp.

I am facing this issue in Magento 2.

Pavan Kumar
  • 1,735
  • 2
  • 28
  • 47
  • my guesses are timezones for mysql and php different, and if this is the case you can synchronise mysql timezone . Have a look here http://stackoverflow.com/questions/3451847/mysql-timezone-change – Gaurav Rai Jan 20 '17 at 15:31

3 Answers3

0

This is an opinionated answer but here goes: Convert the source datetime to a unix timestamp, convert the timezone to + or - a number of seconds (in your case 03:00 would be 3 hours worth of positive second change, or +10800). Arithmetic the two data points. Now you will have a corrected timestamp. Convert back to a datetime object and voila, completed.

Not the most pragmatic but probably one of the simplest to understand options.

David J Eddy
  • 1,999
  • 1
  • 19
  • 37
0

Well i don't know this is a bad idea or what but can we do this?? i have tried this code on magento 1 on list.phtml file

$datetime = new DateTime('2017-01-20T13:59:19+03:00', new DateTimeZone('Asia/Kolkata'));
$new =  $datetime->format('Y-m-d H:i:s e');
$arr = (explode(" ",$new));
$arr2 = explode(":",$arr[1]);
$arr3 = explode(":",$arr[2]);
$vicky = $arr2[0]+$arr3[0];
$arr2[0] = $vicky;
$finaltime = (implode(":",$arr2));
$final =  $arr[0].' '.$finaltime;
echo $final;
Klaus Mikaelson
  • 572
  • 6
  • 17
0

You could try this one. For the timezone, you code get from \Magento\Framework\Stdlib\DateTime\TimezoneInterface::getDefaultTimezone or \Magento\Framework\Stdlib\DateTime\TimezoneInterface::getConfigTimezone

class DateTime
{
    static function convertDateTimeFormat(
        string $originalDatetime,
        string $sourceFormat = 'Y-m-d H:i:s',
        string $destinationFormat = 'Y-m-d H:i:s',
        string $sourceTimezone = 'UTC',
        string $destinationTimezone = null
    ) {
        $sourceTimezoneObj = new \DateTimeZone($sourceTimezone);
        $destinationTimezone = new \DateTimeZone($destinationTimezone ?? $sourceTimezone);

        $dateObject = \Datetime::createFromFormat($sourceFormat, $originalDatetime, $sourceTimezoneObj);

        if ($dateObject === false) {
            throw new \InvalidArgumentException('Please verify your input');
        }

        return $dateObject->setTimezone($destinationTimezone)->format($destinationFormat);
    }
}
minhducck
  • 1
  • 1
  • 2