This article provides a detailed analysis of PHP code for getting the start date and end date of the week (month) of the current date. For more information, see the code.
The code is as follows:
// Obtain the start time and end time of the week of the specified date.
Function getWeekRange ($ date ){
$ Ret = array ();
$ Timestamp = strtotime ($ date );
$ W = strftime ('% u', $ timestamp );
$ Ret ['sdate'] = date ('Y-m-d 00:00:00 ', $ timestamp-($ w-1) * 86400 );
$ Ret ['update'] = date ('Y-m-d 23:59:59 ', $ timestamp + (7-$ w) * 86400 );
Return $ ret;
}
// Obtain the start date and end date of the month of the specified date.
Function getMonthRange ($ date ){
$ Ret = array ();
$ Timestamp = strtotime ($ date );
$ Mdays = date ('t', $ timestamp );
$ Ret ['sdate'] = date ('Y-M-1 00:00:00 ', $ timestamp );
$ Ret ['update'] = date ('Y-m-'. $ mdays. '23:59:59', $ timestamp );
Return $ ret;
}
// Application of the above two functions
Function getFilter ($ n ){
$ Ret = array ();
Switch ($ n ){
Case 1: // yesterday
$ Ret ['sdate'] = date ('Y-m-d 00:00:00 ', strtotime ('-1 DAY '));
$ Ret ['update'] = date ('Y-m-d 23:59:59 ', strtotime ('-1 DAY '));
Break;
Case 2: // this week
$ Ret = getWeekRange (date ('Y-m-D '));
Break;
Case 3: // last week
$ StrDate = date ('Y-m-D', strtotime ('-1 week '));
$ Ret = getWeekRange ($ strDate );
Break;
Case 4: // last week
$ StrDate = date ('Y-m-D', strtotime ('-2 week '));
$ Ret = getWeekRange ($ strDate );
Break;
Case 5: // this month
$ Ret = getMonthRange (date ('Y-m-D '));
Break;
Case 6: // last month
$ StrDate = date ('Y-m-D', strtotime ('-1 month '));
$ Ret = getMonthRange ($ strDate );
Break;
}
Return $ ret;
}