Home > other >  PHP - Trying to calculate difference between dates get 0 as a result
PHP - Trying to calculate difference between dates get 0 as a result

Time:07-31

I am trying to calculate the difference between two dates to get difference in days, months and years but as a result I get 0 on all parameters. I am relatively new to this, for some I am making an obvious mistake, but I cannot understand what I am doing wrong. Would anyone be kind enough to clarify this? I appreciate any answers / help, thanks.

Update

After Markus Zeller's answer I modified my code as follows and it worked. I will make further changes to better suit my needs, but the code as it is works fine. It does not provide the total number of days and months, but these are displayed as age (example 1 year, 3 months and 14 days) and not as (example 1 year 15 months and 471 days). In these two examples the dates were start: 04/15/2021 - end: 07/30/2022

Only problem left

Following the examples above, the correct past days would be 15 (or 471), while I get 14 (or 470). Why is there this 1 day error ?

function difference_between_date() { 

  $data1 = new DateTime(wp_get_current_user()->user_registered); //Registered User Date

  $data2 = new DateTime(); //Current Date


  $interval = $data1->diff($data2);
  $diffInSeconds = $interval->s; //example 45
  $diffInMinutes = $interval->i; //example 15
  $diffInHours   = $interval->h; //example 6
  $diffInDays    = $interval->d; //example 20
  $diffInMonths  = $interval->m; //example 4
  $diffInYears   = $interval->y; //example 2

  echo '<div >days' . wp_kses_post($diffInDays) . '</div>';
  echo '<div >months' . wp_kses_post($diffInMonths) . '</div>';
  echo '<div >years' . wp_kses_post($diffInYears) . '</div>';
  
}   add_shortcode('diff_date', 'difference_between_date');

CodePudding user response:

PHP has very good DateTime functions. Use them for example:

$date1 = new DateTime('2022-07-30 15:00:00');
$date2 = new DateTime('2020-01-29 14:30:00');
$diff = $date2->diff($date1);
print_r($diff);

gives you all the properties you need. In this example 2 years, 6 months, 1 day and 30 mins or 913 days in total.

DateInterval Object
(
    [y] => 2
    [m] => 6
    [d] => 1
    [h] => 0
    [i] => 30
    [s] => 0
    [f] => 0
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 0
    [days] => 913
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)
  • Related