Calculate the difference between timezone dates

Asked

Viewed 893 times

1

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

Assuming a post is from America/Sao_Paulo and another of Europe/Amsterdam.
For each log entry I must keep the user Timezone or the server?

How do I compute the difference when one user is reading another user’s post?
If the São Paulo user accesses the Amsterdam post, how to show that it was the X minutes?

I don’t know the best way to record the input moment of posts...

  • You could have a table in the bank that stores the transactions, save the time of posting and the time of receipt of the product and after that calculate (since you already have the two times saved in bank).

2 answers

1


I suggest you convert to a common Timezone when storing the posting 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');
  • erred in toFormat, I traded for format and it worked, thank you

  • I wrote the code straight from the site. Edited

1

I suggest you save the logs with the server Timezone and calculate the difference at the time of display (as long as you have saved each user’s Timezone).

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

To do this, use the PHP Datetime class (PHP >= 5.2).
Docs.: http://php.net/manual/en/class.datetime.php

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');
  • the 2 answers are practically identical. thank you Lucas

Browser other questions tagged

You are not signed in. Login or sign up in order to post.