How to get week php?

I have tried to solve this question for years now, I thought I found a shorter solution but had to come back again to the long story. This function gives back the right ISO week notation:

``````/**
* calcweek("2018-12-31") => 1901
* This function calculates the production weeknumber according to the start on
* monday and with at least 4 days in the new year. Given that the \$date has
* the following format Y-m-d then the outcome is and integer.
*
* @author M.S.B. Bachus
*
* @param date-notation PHP "Y-m-d" showing the data as yyyy-mm-dd
* @return integer
**/
function calcweek(\$date) {
// 1. Convert input to \$year, \$month, \$day
\$dateset      = strtotime(\$date);
\$year         = date("Y", \$dateset);
\$month        = date("m", \$dateset);
\$day          = date("d", \$dateset);

\$referenceday = getdate(mktime(0,0,0, \$month, \$day, \$year));
\$jan1day      = getdate(mktime(0,0,0,1,1,\$referenceday[year]));

// 2. check if \$year is a  leapyear
if ( (\$year%4==0 && \$year%100!=0) || \$year%400==0) {
\$leapyear = true;
} else {
\$leapyear = false;
}

// 3. check if \$year-1 is a  leapyear
if ( ((\$year-1)%4==0 && (\$year-1)%100!=0) || (\$year-1)%400==0 ) {
\$leapyearprev = true;
} else {
\$leapyearprev = false;
}

// 4. find the dayofyearnumber for y m d
\$mnth = array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334);
\$dayofyearnumber = \$day + \$mnth[\$month-1];
if ( \$leapyear && \$month > 2 ) { \$dayofyearnumber++; }

// 5. find the jan1weekday for y (monday=1, sunday=7)
\$yy = (\$year-1)%100;
\$c  = (\$year-1) - \$yy;
\$g  = \$yy + intval(\$yy/4);
\$jan1weekday = 1+((((intval(\$c/100)%4)*5)+\$g)%7);

// 6. find the weekday for y m d
\$h = \$dayofyearnumber + (\$jan1weekday-1);
\$weekday = 1+((\$h-1)%7);

// 7. find if y m d falls in yearnumber y-1, weeknumber 52 or 53
\$foundweeknum = false;
if ( \$dayofyearnumber <= (8-\$jan1weekday) && \$jan1weekday > 4 ) {
\$yearnumber = \$year - 1;
if ( \$jan1weekday = 5 || ( \$jan1weekday = 6 && \$leapyearprev )) {
\$weeknumber = 53;
} else {
\$weeknumber = 52;
}
\$foundweeknum = true;
} else {
\$yearnumber = \$year;
}

// 8. find if y m d falls in yearnumber y+1, weeknumber 1
if ( \$yearnumber == \$year && !\$foundweeknum) {
if ( \$leapyear ) {
\$i = 366;
} else {
\$i = 365;
}
if ( (\$i - \$dayofyearnumber) < (4 - \$weekday) ) {
\$yearnumber = \$year + 1;
\$weeknumber = 1;
\$foundweeknum = true;
}
}

// 9. find if y m d falls in yearnumber y, weeknumber 1 through 53
if ( \$yearnumber == \$year && !\$foundweeknum ) {
\$j = \$dayofyearnumber + (7 - \$weekday) + (\$jan1weekday - 1);
\$weeknumber = intval( \$j/7 );
if ( \$jan1weekday > 4 ) { \$weeknumber--; }
}

// 10. output iso week number (YYWW)
return (\$yearnumber-2000)*100+\$weeknumber;
}
``````

I found out that my short solution missed the 2018-12-31 as it gave back 1801 instead of 1901. So I had to put in this long version which is correct.

(PHP 4, PHP 5, PHP 7, PHP 8)

dateFormat a Unix timestamp

Description

date(string `\$format`, ?int `\$timestamp` = `null`): string

Parameters

`format`

Format accepted by DateTimeInterface::format().

`timestamp`

The optional `timestamp` parameter is an int Unix timestamp that defaults to the current local time if `timestamp` is omitted or `null`. In other words, it defaults to the value of time().

Return Values

Returns a formatted date string. If a non-numeric value is used for `timestamp`, `false` is returned and an `E_WARNING` level error is emitted.

Errors/Exceptions

Every call to a date/time function will generate a `E_WARNING` if the time zone is not valid. See also date_default_timezone_set()

Changelog

VersionDescription
8.0.0 `timestamp` is nullable now.

Examples

Example #1 date() examples

``` <?php// set the default timezone to use.date_default_timezone_set('UTC');// Prints something like: Mondayecho date("l");// Prints something like: Monday 8th of August 2005 03:12:46 PMecho date('l jS \of F Y h:i:s A');// Prints: July 1, 2000 is on a Saturdayecho "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));/* use the constants in the format parameter */// prints something like: Wed, 25 Sep 2013 15:28:57 -0700echo date(DATE_RFC2822);// prints something like: 2000-07-01T00:00:00+00:00echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));?> ```

You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash.

Example #2 Escaping characters in date()

``` <?php// prints something like: Wednesday the 15thecho date('l \t\h\e jS');?> ```

It is possible to use date() and mktime() together to find dates in the future or the past.

Example #3 date() and mktime() example

``` <?php\$tomorrow  = mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"));\$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));\$nextyear  = mktime(0, 0, 0, date("m"),   date("d"),   date("Y")+1);?> ```

Note:

This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight saving time.

Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines.

Example #4 date() Formatting

``` <?php// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the// Mountain Standard Time (MST) Time Zone\$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm\$today = date("m.d.y");                         // 03.10.01\$today = date("j, n, Y");                       // 10, 3, 2001\$today = date("Ymd");                           // 20010310\$today = date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01\$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.\$today = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001\$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month\$today = date("H:i:s");                         // 17:16:18\$today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)?> ```

To format dates in other languages, IntlDateFormatter::format() can be used instead of date().

Notes

Note:

To generate a timestamp from a string representation of the date, you may be able to use strtotime(). Additionally, some databases have functions to convert their date formats into timestamps (such as MySQL's » UNIX_TIMESTAMP function).

• DateTimeImmutable::__construct() - Returns new DateTimeImmutable object
• DateTimeInterface::format() - Returns date formatted according to given format
• gmdate() - Format a GMT/UTC date/time
• idate() - Format a local time/date part as integer
• getdate() - Get date/time information
• getlastmod() - Gets time of last page modification
• mktime() - Get Unix timestamp for a date
• IntlDateFormatter::format() - Format the date/time value as a string
• time() - Return current Unix timestamp
• Predefined DateTime Constants

How do I get the day 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 can I get a week start and end in PHP?

getStartAndEndDate(\$week, \$year); output: \$return[0] = \$firstDay; \$return[1] = \$lastDay; The return value will be something like an array in which the first entry is the week starting date and the second being the ending date.

How can I get Monday of current week in PHP?

Try this. echo date('Y-m-d', strtotime('last monday', strtotime('next monday'))); It will return current date if today is monday, and will return last monday otherwise.

What's the current week number 2022?

Week 39 is from Monday, September 26, 2022 until (and including) Sunday, October 2, 2022. The highest week number in a year is either 52 or 53. 2022 has 52 weeks.

Tải thêm tài liệu liên quan đến bài viết How to get week php?