Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

PHP get start and end date of a week by weeknumber

I've seen some variants on this question but I believe this one hasn't been answered yet.

I need to get the starting date and ending date of a week, chosen by year and week number (not a date)

example:

input:

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.

OPTIONAL: while we are at it, the date format needs to be Y-n-j (normal date format, no leading zeros.

I've tried editing existing functions that almost did what I wanted but I had no luck so far.

Please help me out, thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using DateTime class:

function getStartAndEndDate($week, $year) {
  $dto = new DateTime();
  $dto->setISODate($year, $week);
  $ret['week_start'] = $dto->format('Y-m-d');
  $dto->modify('+6 days');
  $ret['week_end'] = $dto->format('Y-m-d');
  return $ret;
}

$week_array = getStartAndEndDate(52,2013);
print_r($week_array);

Returns:

Array
(
    [week_start] => 2013-12-23
    [week_end] => 2013-12-29
)

Explained:

  • Create a new DateTime object which defaults to now()
  • Call setISODate to change object to first day of $week of $year instead of now()
  • Format date as 'Y-m-d' and put in $ret['week_start']
  • Modify the object by adding 6 days, which will be the end of $week
  • Format date as 'Y-m-d' and put in $ret['week_end']

A shorter version (works in >= php5.3):

function getStartAndEndDate($week, $year) {
  $dto = new DateTime();
  $ret['week_start'] = $dto->setISODate($year, $week)->format('Y-m-d');
  $ret['week_end'] = $dto->modify('+6 days')->format('Y-m-d');
  return $ret;
}

Could be shortened with class member access on instantiation in >= php5.4.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...