Skip Navigation

[Resolved] Calculate time between two custom date/time fields

This support ticket is created 3 years, 7 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 -
- 13:00 – 18:00 13:00 – 18:00 13:00 – 18:00 14:00 – 18:00 13:00 – 18:00 -

Supporter timezone: America/Jamaica (GMT-05:00)

This topic contains 16 replies, has 3 voices.

Last updated by Shane 3 years, 6 months ago.

Assisted by: Shane.

Author
Posts
#1785515

I would like to calculate time (in hours:minutes) between two custom date/time fields. Is this possible?

#1786473

Hello, there is nothing built-in to Toolset that will calculate values like this, so you would need custom PHP code. Toolset Types date fields store Unix timestamp values, so you would need to understand how to calculate time differences with PHP using Unix timestamps. Something like the shortcode shared in this ticket: https://toolset.com/forums/topic/create-deadline-filed-and-add-it-to-post-grid/

#1788371

So if I were to modify the php something like:

add_shortcode( 'format_date_difference', 'format_date_difference__timesheet_func');
function format_date_difference_timesheet_func($atts = [])
{
  $atts = shortcode_atts([
    'start' => '',
    'end' => '',
    'format' => '%H Hours, %i Minutes',
  ], $atts);
  $work-start = new DateTime($atts['start']);
  $work-end = new DateTime($atts['end']);
  $interval = $work-start->diff($work-end);
  return $interval->format($atts['format']);
}

And then add the shortcode:


[format_date_difference start='[types field="hours-worked" format="h:i"][/types]' end='' format='%H-i Time']

#1789451

Did you have a specific question about those changes? Generally speaking, I have this feedback for you:
1. Do not use "-" characters in PHP variable names. See https://www.php.net/manual/en/language.variables.basics.php
2. You have used the format "h:i" with the start time Types field value, but that only outputs the hour (12-hour clock) and minutes of each date/time. So let's say the start time is one in the afternoon and the end time is one in the morning the following day. The outputs of each shortcode would be:

01:00

and

01:00

If you calculate the difference between dates generated from only these two values, the result is zero hours and zero minutes. In other words, you haven't given the date difference calculation function enough information by outputing only h:i from each field. Check these datetime format, interface, and diff function documentation links:
https://www.php.net/manual/en/datetime.format.php
https://www.php.net/manual/en/class.datetimeinterface.php
hidden link
You must generate more accurate datetime objects to calculate time, using the format and reference documents to output the Types field date values in the proper format.

3. Without providing an "end" datetime value in the format_date_difference shortcode, the difference calculation assumes you want to calculate the difference between the start time and the current time when the page is visited. If I understand correctly, you want the difference between the two custom field values, not the difference from start to now. So you should add the corresponding Types field shortcode in the "end" attribute of the custom shortcode, as you see the start time shortcode in the "start" attribute now.

#1791721

Displaying just the hour:mins is what I want. But I thought that I did put the start & end fields in the function? Isn't that where the calculation happens?

#1796135

Shane
Supporter

Languages: English (English )

Timezone: America/Jamaica (GMT-05:00)

Hi Larry,

Christian is currently on vacation at the moment so I will be handling this thread for him.

Does your current shortcode return the correct value ? Or is it that the formatting is incorrect.

This way I can know how to approach the issue to best help you to resolve it.

Thanks,
Shane

#1799087

No, currently it is not returning anything. I had presented that function as an idea to do what I was trying to do.

#1800025

Shane
Supporter

Languages: English (English )

Timezone: America/Jamaica (GMT-05:00)

Hi Larry,

You can actually do it like this.


add_shortcode( 'format_date_difference', 'format_date_difference__timesheet_func');
function format_date_difference_timesheet_func($atts = [])
{
  $atts = shortcode_atts([
    'start' => '',
    'end' => '',
    'format' => '%H Hours, %i Minutes',
  ], $atts);
$diff = strtotime($atts['end'])->diff(strtotime($atts['start']);
return $diff->format('%h')." Hours ".$diff->format('%i')." Minutes";
}

Please try this and let me know if it helps.
Thanks,
Shane

#1801229

Parse error: syntax error, unexpected ';', expecting ')' in /home/s3361/html/wp-content/themes/Divi-child/functions.php on line 13

Notice: Undefined property: wpdb::$actionscheduler_actions in /home/s3361/html/wp-includes/wp-db.php on line 648
WordPress database error: [Table 's3361.a' doesn't exist]
SELECT a.action_id FROM a WHERE 1=1 AND a.hook='wp_mail_smtp_send_usage_data' AND a.status='pending' ORDER BY a.scheduled_date_gmt ASC LIMIT 0, 1000

Notice: Undefined property: wpdb::$actionscheduler_actions in /home/s3361/html/wp-includes/wp-db.php on line 648
WordPress database error: [Table 's3361.a' doesn't exist]
SELECT a.action_id FROM a WHERE 1=1 AND a.hook='wp_mail_smtp_send_usage_data' AND a.status='pending' ORDER BY a.scheduled_date_gmt ASC LIMIT 0, 1000

#1801599

Shane
Supporter

Languages: English (English )

Timezone: America/Jamaica (GMT-05:00)

Hi Larry,

Try using this

function format_date_difference_timesheet_func($atts = [])
{
  $atts = shortcode_atts([
    'start' => '',
    'end' => '',
    'format' => '%H Hours, %i Minutes',
  ], $atts);
  $start_date = date_create($atts['start']);
  $end_date = date_create($atts['end']);
  $diff = date_diff($end_date, $start_date);
  return $diff->format($atts['format']);
}
add_shortcode( 'format_date_difference', 'format_date_difference_timesheet_func');

Is there a time added to your datepicker? The reason is because without the time, you can only display the days difference.

Example shortcode.

[format_date_difference start="October 6, 2020 12:00" end="October 7, 2020 12:00"]

For further clarification on the functions used I would recommend taking a look here.
hidden link

Thanks,
Shane

#1802453

OK, so I added the shortcode and modified it to include the custom fields that I need to calculate:

[format_date_difference start="start-time" end="end-time"]

Then I get:

Warning: date_diff() expects parameter 1 to be DateTimeInterface, bool given in /home/s3361/html/wp-content/themes/Divi-child/functions.php on line 14

Fatal error: Uncaught Error: Call to a member function format() on bool in /home/s3361/html/wp-content/themes/Divi-child/functions.php:15 Stack trace: #0 /home/s3361/html/wp-includes/shortcodes.php(343): format_date_difference_timesheet_func(Array, '', 'format_date_dif...') #1 [internal function]: do_shortcode_tag(Array) #2 /home/s3361/html/wp-includes/shortcodes.php(218): preg_replace_callback('/\\[(\\[?)(format...', 'do_shortcode_ta...', '<td>[wpv-post-d...') #3 /home/s3361/html/wp-includes/class-wp-hook.php(287): do_shortcode('<td>[wpv-post-d...') #4 /home/s3361/html/wp-includes/plugin.php(206): WP_Hook->apply_filters('<td>[wpv-post-d...', Array) #5 /home/s3361/html/wp-content/plugins/wp-views/application/models/shortcode/post/body.php(260): apply_filters('the_content', '') #6 /home/s3361/html/wp-content/plugins/wp-views/application/models/shortcode/base_view.php(32): WPV_Shortcode_Post_Body->get_value(Array, '') #7 /home/s3361/html/wp-includes/shortcodes.php(343): WPV_Shortcode_Base_View->render(Array, '', 'wpv-post-b in /home/s3361/html/wp-content/themes/Divi-child/functions.php on line 15

#1803225

Shane
Supporter

Languages: English (English )

Timezone: America/Jamaica (GMT-05:00)

Hi Larry,

You need to provide the actual date in the shortcode and not the slug of the fields.

Example.

[format_date_difference start="October 6, 2020 12:00" end="October 7, 2020 12:00"]

In your case it would be.


[format_date_difference start="shortcode for start" end="shortcode for end"]

Not you must set the shortcode to display the time as well example
[types field="my-start-date" format="F j, Y, g:i a"][/types]

Please let me know if this clarifies this for you.

Thanks,
Shane

#1803935
calctest.PNG

It doesn't appear to be calculating properly. If you look at the screen shot, the the second to last column is the correct hours calculated and the last column uses the function.

#1804669

Shane
Supporter

Languages: English (English )

Timezone: America/Jamaica (GMT-05:00)

Hi Larry,

Thats because this is spanning days now.

So you need to replace the line below

 'format' => '%H Hours, %i Minutes',

with

'format' => '%a Days %H Hours, %i Minutes',

This should also account for the days.

Thanks,
Shane

#1807843
Capture.PNG

It doesn't total.

This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.