Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - get last week number in year

Tags:

php

Tell me please how to get the last number of weeks in a year?

like image 832
palych063 Avatar asked Jul 23 '10 15:07

palych063


People also ask

How to find week number in php?

How to get the week number from a date. To get the ISO week number (1-53) of a date represented by a Unix timestamp, use idate('W', $timestamp ) or strftime('%-V', $timestamp ) . For a date represented by a DateTime instance, use intval( $dateTime ->format('W')) .

How can I get last week start and end date in PHP?

date("m/d/Y", strtotime("last week monday")); date("m/d/Y", strtotime("last week sunday")); It will give the date of Last week's Monday and Sunday.


2 Answers

function getIsoWeeksInYear($year) {     $date = new DateTime;     $date->setISODate($year, 53);     return ($date->format("W") === "53" ? 53 : 52); } 

The o date format gives the ISO-8601 year number. We can use this, and the fact that "invalid" dates are automatically rolled around to make valid ones (2011-02-31 gives 2011-03-03), to determine if a given year has 53 weeks. If does not, then it must have 52.

See also, date format characters and DateTime::setISODate() manual pages.

like image 153
salathe Avatar answered Sep 23 '22 00:09

salathe


In ISO-8601 specification, it says that December 28th is always in the last week of its year.
Based on that, we can simply create that date, and see in what week it is:

$dt = new DateTime('December 28th');
echo $dt->format('W'); # 52

$dt = new DateTime('December 28th, 2009');
echo $dt->format('W'); # 53

demo

... or if you are using date() and strtotime() functions: echo date('W', strtotime('December 28th')); # 52

like image 22
Glavić Avatar answered Sep 21 '22 00:09

Glavić