0

I created a custom form on a WordPress website that lets users click a button to start recording time, and then later on another page there is a different form that lets the user stop recording time.

When they submit the first form to start recording time, I add this post meta to the database:

/* Start timer */
$now = strtotime('now');
update_post_meta( $post_id, 'start_time', $now);

An example value in the database is something like this: 1627607870

When they submit the second form later to stop recording time, I add this post meta to the database:

/* End timer */
$now = strtotime('now');
update_post_meta( $post_id, 'end_time', $now);

An example value in the database is something like this: 1627607890

To calculate how much time had passed, I do simple subtraction:

/* Total time */
$start_time     = get_post_meta($post_id, 'start_time', TRUE);
$end_time       = get_post_meta($post_id, 'end_time', TRUE);
$total_time     = $end_time - $start_time;
echo $total_time;

...which, using the example values shown above $total_time would return 20.

This all works fine - for me. But, I have some users in different countries who say that the total time returned is completely wrong, sometimes even showing what appears to be long completely random numbers.

So I am wondering if there something wrong with my approach? My gut feeling is that different timezones could affect $total_time but I might be wrong.

3
  • Have a look at the php manual: Warning The Unix timestamp that this function returns does not contain information about time zones. In order to do calculations with date/time information, you should use the more capable DateTimeImmutable.
    – digijay
    Jul 30, 2021 at 1:46
  • I saw that but I'm not convinced it matters, but maybe there's something I don't understand about this. The way I see it, the values of $now, $start_time and $end_time are established by getting the number of seconds since the 0:00:00 January 1,1970 GMT.
    – User_FTW
    Jul 30, 2021 at 2:35
  • That's right, unix timestamps usually don't contain timezone information. I'm not sure what's going on there
    – digijay
    Jul 30, 2021 at 2:37

3 Answers 3

0

You could try calculating time from GMT. this way, you can atleast get assured if it is a timezone issue or not.

0

You can use the function current_time(timestamp); it brings the time zone set in the WP admin.

The WordPress has some Constants to work with time:

MINUTE_IN_SECONDS 

HOUR_IN_SECONDS 

DAY_IN_SECONDS 

WEEK_IN_SECONDS

MONTH_IN_SECONDS 

YEAR_IN_SECONDS
0

Another WordPress Function of time duration is human_readable_duration()

Convert a duration to human readable format.

https://developer.wordpress.org/reference/functions/human_readable_duration/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.