Convert a DateTime object to a friendly time display

Source: Internet
Author: User
Convert a DateTime object to a friendly time display using DateInterval in PHP 5.x




  1. /**
  2. * Friendly Date and time
  3. *
  4. * Date Time @param datetime $datetime
  5. * @param int $size Precise in-place number
  6. * @throws \invalidargumentexception
  7. * @return String
  8. */
  9. function Friendly_date ($datetime, $size =1)
  10. {
  11. if (Is_int ($datetime)) {
  12. $datetime = new \datetime ($datetime);
  13. }
  14. if (! ( $datetime instanceof \datetime)) {
  15. throw new \invalidargumentexception (' invalid ' DateTime "Object");
  16. }
  17. $now = new \datetime ();
  18. $interval = $now->diff ($datetime);
  19. $intervalData = Array (
  20. $interval->y, $interval->m, $interval->d,
  21. $interval->h, $interval->i, $interval->s,
  22. );
  23. $intervalFormat = Array (' Year ', ' Month ', ' Day ', ' hour ', ' minute ', ' second ');
  24. foreach ($intervalData as $index = = $value) {
  25. if ($value) {
  26. $intervalData [$index] = $value. $intervalFormat [$index];
  27. } else {
  28. Unset ($intervalData [$index]);
  29. Unset ($intervalFormat [$index]);
  30. }
  31. }
  32. Return implode (", Array_slice ($intervalData, 0, $size));
  33. }
Copy Code
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.