1

I would like to calculate the number of days past since a users creation date. This is what I have done so far:

$user = \Drupal::currentUser();
$registrationdate = getdate($user->getCreatedTime());
$today = getdate();
$daypast = date_diff($regdate, $today);

This results in the following error:

date_diff() expects parameter 1 to be DateTimeInterface

How can I solve this and get the number of days past since the users registration date?

  • 1
    Guess I could point out the obvious. Your variables are wrong. Not $regdate it is $registrationdate. – Brady Apr 1 '17 at 20:51
  • This question may be a duplicate of calculate time between dates, there is a nice solution, look on comments, there is a link to a youtube demo. it needs rules module. – pinueve Apr 1 '17 at 21:50
  • @Brady comment explains the error message, while mpdonadio answer explains the Drupal code to use. – kiamlaluno Apr 2 '17 at 9:22
3

This depends on what you need to do with it. If you truly just need the number of days, then this will work

$user = \Drupal::currentUser();
$created = new \DateTime('@' . $user->getAccount()->getCreatedTime());
$interval = $created->diff(new \DateTime());
$days1 = $interval->d
$days2 = intval($interval->format('%d'));

Here $days1 and $days2 should give you the same value. See the docs for \DateTime and \DateInterval for more information.

If you need a nifty string for output purposes, then check out DateFormatter::formatTimeDiffSince() and friends:

$user = \Drupal::currentUser();
$created = $user->getAccount()->getCreatedTime();
/** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
$date_formatter = \Drupal::service('date.formatter');
$created_since = $date_formatter->formatTimeDiffSince($created);

and then $created_since will be a string like '7 weeks 2 days'. You can also use the 'Time ago' formatter directly in the entity rendering configuration. The default view for the accounts listing does this.

  • +1 for DateFormatter::formatTimeDiffSince(). I doubt the OP would want to show the difference in days when a year is past. 700 days ago is not much helpful. – kiamlaluno Apr 2 '17 at 7:26
  • This question may be a duplicate of calculate time between dates, drupal.stackexchange.com/questions/149442/…, there is a nice solution, look on comments, there is a link to a youtube demo. it needs rules module. – pinueve Apr 4 '17 at 22:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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