Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the "first day of the week" to Thursday in PHP

Tags:

function

date

php

I want to set the first day of the week to Thursday (not Sunday or Monday), because it's the company's cut-off date.

I already have a code to determine the current week number of a date but it starts in Sunday or Monday.

How to modify these to my preference?

function findweek($date) {
    $monthstart=date("N",strtotime(date("n/l/Y",strtotime($date))));
    $newdate=(date("j",strtotime($date))+$monthstart)/7;
    $ddate=floor($newdate);
    if($ddate != $date) {
        $ddate++;
    }
    return $ddate;
}
like image 617
Rayden Black Avatar asked Sep 15 '15 03:09

Rayden Black


People also ask

How do I get the start of the week in PHP?

Use strtotime() function to get the first day of week using PHP. This function returns the default time variable timestamp and then use date() function to convert timestamp date into understandable date.

How do you determine the first day of the week?

To get the first day of the current week, get the day of the month, subtract the day of the week and add 1 to consider Monday the first day of the week.

How can get first and last day of month in PHP?

php $query_date = '2010-02-04'; // First day of the month. echo date('Y-m-01', strtotime($query_date)); // Last day of the month. echo date('Y-m-t', strtotime($query_date));


1 Answers

http://php.net/manual/en/datetime.formats.relative.php says that as of PHP version 5.6.23, 7.0.8 "Weeks always start on monday. Formerly, sunday would also be considered to start a week." That said, is your problem that the number of weeks returned might be incorrect depending on whether today falls on or before Thursday of the current week? Maybe try something like this:

$date = new DateTime();
$week = intval($date->format('W'));
$day = intval($date->format('N'));
echo $day < 4 ? $week-1 : $week;

If subtracting 1 isn't the answer you could play around with addition/subtraction, comparing the result with the actual answer you know to be true until you get the right formula. Hope this helps!

like image 194
robbymarston Avatar answered Oct 17 '22 20:10

robbymarston