skip to Main Content

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

Answers


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

    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
  3. 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/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search