search
HomeBackend DevelopmentPHP TutorialPHP calculates the number of days difference between dates (the time difference between any time and the current time)

  1. function count_days($a,$b){
  2. $a_dt=getdate($a);
  3. $b_dt=getdate($b);
  4. $a_new=mktime(12,0, 0,$a_dt['mon'],$a_dt['mday'],$a_dt['year']);
  5. $b_new=mktime(12,0,0,$b_dt['mon'],$b_dt[ 'mday'],$b_dt['year']);
  6. return round(abs($a_new-$b_new)/86400);
  7. }
  8. //How many days are there between today and October 11, 2008
  9. $date1= strtotime(time());
  10. $date1=strtotime('10/11/2008');
  11. $result=count_days($date1,$date2);
  12. echo $result;
  13. ?>
Copy code

Method 2:

  1. //How many days are there between today and September 9, 2008
  2. $Date_1=date("Y-m-d");
  3. $Date_2="2008-10-11";
  4. $d1 =strtotime($Date_1);
  5. $d2=strtotime($Date_2);
  6. $Days=round(($d2-$d1)/3600/24);
  7. echo "The difference between today and October 11, 2008". $Days."Days";
  8. ?>
Copy code

PHP Get the time difference between any time and the current time

Code:

  1. #Function: Get the time difference between any time and the current time
  2. function QueryDays($datestr){
  3. #Format time
  4. $da=preg_split("/(-| |:)/i ",$datestr);
  5. $nowyear=date("Y");
  6. $nowmon=date("n");
  7. $nowday=date("d");
  8. $nowtimes=mktime(0,0,0 ,$nowmon,$nowday,$nowyear);
  9. $pdtimes= mktime(0,0,0,$nowmon,$nowday,$nowyear-1);
  10. $bjtimes= mktime(0,0,0,$da[ 1],$da[2],$da[0]);
  11. #Judge whether the time given is within one year
  12. if ($bjtimes>=$pdtimes and $bjtimesreturn ( floor(strftime("%j",mktime(0,0,0,$nowmon,$nowday,$nowyear)-mktime($da[3],$da[4],$da[5],$da[ 1],$da[2],$da[0]))));
  13. }else{
  14. $loop=$nowyear-$da[0];
  15. $totaldays=(floor(strftime("%j", mktime(0,0,0,$nowmon,$nowday,$nowyear)-mktime(0,0,0,1,1,$nowyear))));
  16. for($i=1;$ifor($j=12;$j>=1;$j--){
  17. if ($da[0]==$nowyear-$i and $da[1]==$ j){
  18. $days=MonDays($nowyear-$i,$j);
  19. return $totaldays+=$days-$da[2];
  20. break;
  21. }else{
  22. $days=MonDays($nowyear-$ i,$j);
  23. $totaldays+=$days;
  24. }//end else
  25. }//end for
  26. }//end for
  27. }//end else
  28. }//end function
  29. #Get the number of days in the month
  30. function MonDays($year,$month){
  31. switch ($month){
  32. case "1":
  33. case "3":
  34. case "5":
  35. case "7":
  36. case "8":
  37. case "10":
  38. case "12": $days=31;break;
  39. case "4":
  40. case "6":
  41. case "9":
  42. case "11": $days=30;break;
  43. case "2":
  44. if (checkdate($month,29,$year)){
  45. $days=29;
  46. }else{
  47. $days=28;
  48. }//end else
  49. break;
  50. }//end switch
  51. return $days;
  52. }//end function
  53. $datestr="2002-1-14 9:47:20";
  54. echo QueryDays($datestr);
  55. ?>
Copy code

PHP Calculate the year, month, hour, minute and second difference between two times

How to calculate the difference between two times in years, months, hours, minutes and seconds in PHP

First convert the two times into timestamps, then subtract them to get the seconds difference between the two times, and finally do some arithmetic to get the year, month, day, hour, minute and second difference between the two times.

Code:

  1. $time1 = "2008-6-15 11:49:59"; //The first time
  2. $time2 = "2007-5-5 12:53:28"; //The second time
  3. $t1 = strtotime($time1);
  4. $t2 = strtotime($time2);
  5. $t12 = abs($t1-$t2);
  6. $start = 0;
  7. $string = " The difference between the two times: ";
  8. $y = floor($t12/(3600*24*360));
  9. if($start || $y )
  10. {
  11. $start = 1;
  12. $t12 -= $y *3600*24*360;
  13. $string .= $y."year";
  14. }
  15. $m = floor($t12/(3600*24*31));
  16. if($start || $m)
  17. {
  18. $start = 1;
  19. $t12 -= $m*3600*24*31;
  20. $string .= $m."month";
  21. }
  22. $d = floor($t12/(3600*24)) ;
  23. if($start || $d)
  24. {
  25. $start = 1;
  26. $t12 -= $d*3600*24;
  27. $string .= $d."天";
  28. }
  29. $h = floor ($t12/(3600));
  30. if($start || $h)
  31. {
  32. $start = 1;
  33. $t12 -= $h*3600;
  34. $string .= $h."hour";
  35. }
  36. $s = floor($t12/(60));
  37. if($start || $s)
  38. {
  39. $start = 1;
  40. $t12 -= $s*60;
  41. $string .= $s ."minutes";
  42. }
  43. $string .= "{$t12} seconds";
  44. echo $string;
  45. ?>
Copy code


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools