An interesting date logic processing in php

  • 2020-05-16 06:27:21
  • OfStack

I dealt with a very small problem today.
The demand is such that from Monday to Sunday, you can only see the data from last week to last Sunday.
You can query the range directly from the database by the date field.
But you need PHP to generate the start and end dates.

At the beginning, I just did it this way.
 
$start_date = date('Y-m-d' , strtotime("-2 week monday")); 
$end_date = date('Y-m-d' , strtotime("$start_date +6 day")); 

This is fine if the date is 2011-07-19, $start_date= 2011-07-11.
If the date is 2011-07-18, $start_date will be equal to 2011-07-04, which is still alive last week.

So we did it a different way
 
$getWeekDay = date("w"); 
$startDay = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - $getWeekDay + 1 - 7, date("Y"))); 
$endDay = date("Y-m-d", strtotime("+6 day $startDay")); 

If the date is 2011-07-19, $start_date= 2011-07-11 this is fine, as we would expect.
If the date is 2011-07-24, we expect $start_date to be 2011-07-11, but we actually return 2011-07-18.

I had to change my methods
 
$getWeekDay = date("N") ; 
$startDay = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - $getWeekDay + 1 - 7, date("Y"))); 
$endDay = date("Y-m-d", strtotime("+6 day $startDay")); 

This is OK.

Related articles: