Calculate difference between dates with time zone

1

I need to calculate the difference between 2 dates with different time zone:
The calculation is between the post date and the current date.

  

Assuming a post is America/Sao_Paulo and another post Europe/Amsterdam .
  For each registry entry should I keep either the user's timezone or the server's timezone?

How do I compute the difference when a user reads the other's post?
If the user of São Paulo accesses the post of Amsterdam, how to show that it was X minutes?

I do not know the best way to record the moment of entry of the posts ...

    
asked by anonymous 24.07.2014 / 05:38

2 answers

1

I suggest that you make the conversion to a common timezone by storing the post date (server timezone for example).

When displaying the date to the user, convert the date stored on the server using DateTime

<?php

// String timezone - America/Sao_Paulo exemplo
$timezoneServer = $config['timezoneDefault'];

$date = new DateTime('2014-07-25', new DateTimeZone($timezoneServer));
// Pode-se omitir o segundo parametro para usar o padrão do servidor
// $date = new DateTime('2014-07-25);

// Rotina para recuperar o Timezone do usuário
$userTimezone = $userModel->getUserTimeZone();

// Recupera a data do post e converte para a Timezone do usuário
$postDate = new DateTime($post->date, new DateTimeZone($userTimezone));

// "P" exibe a representação em relação a GMT (-03:00, -02:30)
echo $postDate->format('Y-m-d  H:i:sP');
    
24.07.2014 / 13:20
1

I suggest saving the records to the timezone of the server and calculating the difference at the moment of displaying (counting that you have saved the timezone of each user).

  • When you see that the post was X minutes, just calculate the difference between now and the time of posting.
  • When displaying the post date and time, compute the difference between server timezone and user timezone.

To do this, use the PHP DateTime class (PHP > = 5.2). Docs: link

Example:

// cria obj com a tz do servidor
$datetime = new DateTime($post->datetime);
// seta a tz do obj com a tz do usuário (isso já converte a datetime do post)
$datetime->setTimezone(new DateTimeZone($user->timezone));
// imprime
echo $datetime->format('d/m/Y H:i');
    
24.07.2014 / 13:33