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
Release: 2024-11-30 04:57:10
Original
325 people have browsed it

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'));
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template