1

Am saving time in integer format in mysql but its saved on a different timezone

This is the code that a using

$model->created_at = time();

This sets time in integer format eg :1483881886

The problem is that when i reconvert this time to hrs minutes and sec it points into a different timezone

I have also tried

date_default_timezone_set('Africa/Nairobi');
then 
$model->created_at = time();  //the timezone is not set

How do i configure timezone in the unix time() function

Geoff
  • 6,277
  • 23
  • 87
  • 197

1 Answers1

2

time() return always unix timestamp referred to GMT http://php.net/manual/en/function.time.php

But, after got $time in unix timestamp GMT, you can set timezone you want.

<?php
// If in php.ini default timezone is not set
date_default_timezone_set('Africa/Nairobi');

// Time in Unix timestamp GMT
$t = time();

$dt = DateTime::createFromFormat('U', $t);

// From Unix time GMT to Africa/Nairobi
$dt->setTimezone(new DateTimeZone('Africa/Nairobi'));
echo 'Time GMT to Africa/Nairobi: '.$dt->format('Y-m-d H:i:s');

// From Unix time GMT to Europe/Rome
$dt->setTimezone(new DateTimeZone('Europe/Rome'));
echo 'Time GMT to Europe/Rome: '.$dt->format('Y-m-d H:i:s');

?>
Fabrizio Caldarelli
  • 2,982
  • 11
  • 14
  • How do i format in unix time instead of y m d from this: {$dt->format('Y-m-d H:i:s');}} that is to get integers – Geoff Jan 08 '17 at 14:41
  • Unix timestamp is by definition referred to GMT. Check this post: http://stackoverflow.com/questions/8668108/how-to-get-unix-timestamp-in-php-based-on-timezone – Fabrizio Caldarelli Jan 08 '17 at 14:46
  • so in other words it means that when saving unix timestamp(in integers ) its saved according to gmt but when outputting it its when you add the timezone to match the current time – Geoff Jan 08 '17 at 14:52
  • Yes, but only when you format output date in format different from timestamp ( 'U' format in date_format ) – Fabrizio Caldarelli Jan 08 '17 at 15:19
  • Thanks saved alot of time, Ive also found out that my php.ini was set to Germany and by setting to Africa/Nairobi also solves this plus your solution also works – Geoff Jan 08 '17 at 15:28