Home >Backend Development >PHP Tutorial >How to Get the First Day of the Week in PHP?

How to Get the First Day of the Week in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-30 04:57:10382browse

How to Get the First Day of the Week in PHP?

How to Retrieve the First Day of the Week in PHP

Determining the first day of the week can be essential for date-related applications. In PHP, this task can be effortlessly accomplished using built-in date functions.

Method:

To retrieve the first day of the week for a given date in MM-dd-yyyy format, follow these steps:

  1. Determine the Day of the Week:

    • Use date('w') to retrieve the day of the week as a number (0-6), where 0 represents Sunday and 6 represents Saturday.
  2. Calculate the First Day of the Week:

    • Use strtotime('-'.$day.' days') to subtract the day of the week from the current date. This will give you the date for the previous Sunday.
  3. Format the Result:

    • Use date('m-d-Y') to format the result as mm-dd-yyyy.

Example Code:

The following code demonstrates how to implement the above method:

$day = date('w');
$week_start = date('m-d-Y', strtotime('-'.$day.' days'));

The variable $week_start will now hold the date for the previous Sunday, which is the first day of the current week.

Additional Notes:

  • The resulting date will be in the locale's timezone.
  • To obtain the first day of the current week, replace '-'.$day.' days' in the above code with '0 days'.

The above is the detailed content of How to Get the First Day of the Week in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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