13 November 2023

This PHP code snippet provides a convenient way to determine the start and end days of the current week based on a user-specified first day. By setting the `$week_start_day` variable (0 for Sunday, 1 for Monday), the code calculates the beginning and end of the week, considering the current date and time. The resulting DateTime objects, represented by `$this_week_first_day` and `$this_week_last_day`, are then modified to reflect the precise start and end times of the week.

Source code viewer
  1. // PHP Code for Determining Start and End Days of the Week Based on a Specified First Day
  2.  
  3. // Define the starting day of the week (0 for Sunday, 1 for Monday)
  4. $week_start_day = 0;
  5.  
  6. // Create DateTime objects for the current date and time
  7. $date_time_from = new DateTime('now');
  8. $date_time_to = clone $date_time_from;
  9.  
  10. // Calculate the first day of the current week
  11. $this_week_first_day =
  12. $date_time_from->setISODate(
  13. $date_time_from->format('Y'),
  14. $date_time_from->format('W'),
  15. $week_start_day
  16. );
  17.  
  18. // Calculate the last day of the current week
  19. $this_week_last_day =
  20. $date_time_to->setISODate(
  21. $date_time_to->format('Y'),
  22. $date_time_to->format('W'),
  23. (6 + $week_start_day)
  24. );
  25.  
  26. // Set the time to the start of the day and end of the day, respectively
  27. $this_week_first_day->modify('00:00:00.000000');
  28. $this_week_last_day->modify('23:59:59.999999');
  29.  
  30. // Now, $this_week_first_day and $this_week_last_day represent the start and end of the current week.
Programming Language: PHP