Example 1
Convert the date directly
The code is as follows: |
Copy code |
Function daysbetweendates ($ date1, $ date2 ){ $ Date1 = strtotime ($ date1 ); $ Date2 = strtotime ($ date2 ); $ Days = ceil (abs ($ date1-$ Date 2)/86400 ); Return $ days; } |
Example 2
The code is as follows: |
Copy code |
<? Php Functionmaketime ($ date) { List ($ year, $ month, $ day) = explode ('-', $ date ); Returnmktime (0, 0, 0, $ month, $ day, $ year ); } $ Date1 = '2017-01-08 '; $ Date2 = '2017-03-01 '; $ D = (maketime ($ date2)-maketime ($ date1)/(24x3600 ); Echo 'difference $ d Day '; ?> |
Example 3
PHP calculates the year, month, week, and number of days between two dates.
The code is as follows: |
Copy code |
<? Php Function format ($ a, $ B ){ // Check the size of two dates. The default value is "first small" and "later". If the former value is greater than the latter value, the positions are exchanged to ensure the former value is greater than the former value. If (strtotime ($ a)> strtotime ($ B) list ($ a, $ B) = array ($ B, $ ); $ Start = strtotime ($ ); $ Stop = strtotime ($ B ); $ Extend = ($ stop-$ start)/86400; $ Result ['extends '] = $ extend; If ($ extend <7) {// returns the number of days if it is less than 7 days $ Result ['Daily '] = $ extend; } Elseif ($ extend <= 31) {// The number of weeks is returned if it is less than 28 days. Because the leap year meets If ($ stop = strtotime ($ a. '+ 1 month ')){ $ Result ['monthly '] = 1; } Else { $ W = floor ($ extend/7 ); $ D = ($ stop-strtotime ($ a. '+'. $ w. 'Week ')/86400; $ Result ['weekly '] = $ w; $ Result ['Daily '] = $ d; } } Else { $ Y = floor ($ extend/365 ); If ($ y> = 1) {// if it is more than one year $ Start = strtotime ($ a. '+'. $ y. 'Year '); $ A = date ('Y-m-D', $ start ); // Determine whether it has been a year. If not, subtract it. If ($ start> $ stop ){ $ A = date ('Y-m-D', strtotime ($ a. '-1 month ')); $ M = 11; $ Y --; } $ Extend = ($ stop-strtotime ($ a)/86400; } If (isset ($ m )){ $ W = floor ($ extend/7 ); $ D = $ extend-$ w * 7; } Else { $ M = isset ($ m )? $ M: round ($ extend/30 ); $ Stop> = strtotime ($ a. '+'. $ m. 'Month ')? $ M: $ m --; If ($ stop> = strtotime ($ a. '+'. $ m. 'Month ')){ $ D = $ w = ($ stop-strtotime ($ a. '+'. $ m. 'month')/86400; $ W = floor ($ w/7 ); $ D = $ d-$ w * 7; } } $ Result ['early '] = $ y; $ Result ['monthly '] = $ m; $ Result ['weekly '] = $ w; $ Result ['Daily '] = isset ($ d )? $ D: null; } Return array_filter ($ result ); } Print_r (format ('2017-10-1 ', '2017-12-15 ')); ?> |