php PHP通过weeknumber获取一周的开始和结束日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4861384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP get start and end date of a week by weeknumber
提问by Pieter888
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.
可选:虽然我们在这里,但日期格式需要是Y-n-j
(正常日期格式,没有前导零。
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.
请帮助我,提前致谢。
采纳答案by Roham Rafii
Many years ago, I found this function:
多年前,我发现了这个功能:
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);
回答by user3108829
Using DateTimeclass:
使用DateTime类:
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']
- 创建一个默认为 now() 的新 DateTime 对象
- 调用 setISODate 将对象更改为 $year 的 $week 的第一天而不是 now()
- 将日期格式化为 'Ymd' 并放入 $ret['week_start']
- 通过添加 6 天来修改对象,这将是 $week 的结束
- 将日期格式化为 'Ymd' 并放入 $ret['week_end']
A shorter version (works in >= php5.3):
较短的版本(适用于 >= 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 instantiationin >= php5.4.
回答by Henry Ohanga
We can achieve this easily without the need for extra computations apart from those inherent to the DateTimeclass.
除了DateTime类固有的计算之外,我们可以轻松实现这一点,而无需额外的计算。
function getStartAndEndDate($year, $week)
{
return [
(new DateTime())->setISODate($year, $week)->format('Y-m-d'), //start date
(new DateTime())->setISODate($year, $week, 7)->format('Y-m-d') //end date
];
}
The setISODate()
function takes three arguments: $year
, $week
, and $day
respectively, where $day
defaults to 1 - the first day of the week. We therefore pass 7 to get the exact date of the 7th day of the $week
.
该setISODate()
函数采用三个参数:$year
、$week
和$day
分别,其中$day
默认为 1 - 一周的第一天。因此,我们通过 7 来获得 . 的第 7 天的确切日期$week
。
回答by tripper54
Slightly neater solution, using the "[year]W[week][day]" strtotime format:
稍微简洁的解决方案,使用“[year]W[week][day]”strtotime 格式:
function getStartAndEndDate($week, $year) {
// Adding leading zeros for weeks 1 - 9.
$date_string = $year . 'W' . sprintf('%02d', $week);
$return[0] = date('Y-n-j', strtotime($date_string));
$return[1] = date('Y-n-j', strtotime($date_string . '7'));
return $return;
}
回答by Claudiu Creanga
shortest way to do it:
最短的方法:
function week_date($week, $year){
$date = new DateTime();
return "first day of the week is ".$date->setISODate($year, $week, "1")->format('Y-m-d')
."and last day of the week is ".$date->setISODate($year, $week, "7")->format('Y-m-d');
}
echo week_date(12,2014);
回答by Nasser Ali Karimi
You can get the specific day of week from date as bellow that I get the first and last day
您可以从日期中获取一周中的特定日期,如下所示我得到第一天和最后一天
$date = date_create();
// get the first day of the week
date_isodate_set($date, 2019, 1);
//convert date format and show
echo date_format($date, 'Y-m-d') . "\n";
// get the last date of the week
date_isodate_set($date, 2019, 1, 7);
//convert date format and show
echo date_format($date, 'Y-m-d') . "\n";
Output =>
2018-12-31
2019-01-06
输出 =>
2018-12-31
2019-01-06
回答by FirePanther
The calculation of Roham Rafii is wrong. Here is a short solution:
Roham Rafii 的计算是错误的。这是一个简短的解决方案:
// week number to timestamp (first day of week number)
function wn2ts($week, $year) {
return strtotime(sprintf('%dW%02d', $year, $week));
}
if you want the last day of the week number, you can add up 6 * 24 * 3600
如果你想要星期几的最后一天,你可以加起来 6 * 24 * 3600
回答by bezz
This is an old question, but many of the answers posted above appear to be incorrect. I came up with my own solution:
这是一个老问题,但上面发布的许多答案似乎都不正确。我想出了我自己的解决方案:
function getStartAndEndDate($week, $year){
$dates[0] = date("Y-m-d", strtotime($year.'W'.str_pad($week, 2, 0, STR_PAD_LEFT)));
$dates[1] = date("Y-m-d", strtotime($year.'W'.str_pad($week, 2, 0, STR_PAD_LEFT).' +6 days'));
return $dates;
}
回答by Catalin Marin
First we need a day from that week so by knowing the week number and knowing that a week has seven days we are going to do so the
首先,我们需要该周的一天,因此通过知道周数并知道一周有 7 天,我们将这样做
$pickADay = ($weekNo-1) * 7 + 3;
this way pickAday will be a day in our desired week.
这样,pickAday 将是我们想要的一周中的一天。
Now because we know the year we can check which day is that.
things are simple if we only need dates newer than unix timestamp
We will get the unix timestamp for the first day of the year and add to that 24*3600*$pickADay
and all is simple from here because we have it's timestamp we can know what day of the week it is and calculate the head and tail of that week accordingly.
现在因为我们知道年份,所以我们可以检查那是哪一天。如果我们只需要比 unix 时间戳新的日期,事情24*3600*$pickADay
就很简单了我们将获得一年中第一天的 unix 时间戳并将其添加到其中,一切都很简单,因为我们有了它的时间戳,我们可以知道它是一周中的哪一天并相应地计算该周的头部和尾部。
If we want to find out the same thing of let's say 12th week of 1848 we must use another approach as we can not get the timestamp. Knowing that each year a day advances 1 weekday meaning (1st of november last year was on a sunday, this year is on a monday, exception for the leap years when it advances 2 days I believe, you can check that ). What I would do if the year is older than 1970 than make a difference between it and the needed year to know how many years are there, calculate the day of the week as my pickADay was part of 1970, shift it back one weekday for each. $shiftTimes = ($yearDifference + $numberOfLeapYears)%7
, in the difference. shift the day backwords $shiftTimes, then you will know what day of the week was that day those years ago, then find the weekhead and weektail. Same thing can be used also for the future if it seems simpler. Try it if it works and tell me if it does not.
如果我们想找出同样的事情,比如说 1848 年的第 12 周,我们必须使用另一种方法,因为我们无法获得时间戳。知道每年一天提前 1 个工作日的意思(去年 11 月 1 日是星期日,今年是星期一,闰年例外,我相信它提前 2 天,你可以检查一下)。如果这一年早于 1970 年,我会怎么做,而不是在它和需要的年份之间产生差异以知道那里有多少年,计算一周中的哪一天,因为我的 pickADay 是 1970 年的一部分,将每个工作日移回一个工作日.$shiftTimes = ($yearDifference + $numberOfLeapYears)%7
,不同之处。shift the day backwords $shiftTimes,然后你就会知道那些年前那一天是星期几,然后找到weekhead和weektail。如果看起来更简单,同样的事情也可以用于未来。试试看是否有效,如果无效告诉我。
回答by Kai Noack
For documentation (since Google ranks this question first when searching for "php datetime start end this week").
对于文档(因为 Google 在搜索“php datetime start end this week”时将这个问题排在第一位)。
If you need the startdate and enddate for the current week(using DateTime):
如果您需要本周的开始日期和结束日期(使用日期时间):
$dateTime = new DateTime('now');
$monday = clone $dateTime->modify(('Sunday' == $dateTime->format('l')) ? 'Monday last week' : 'Monday this week');
$sunday = clone $dateTime->modify('Sunday this week');
var_dump($monday->format('Y-m-d')); // e.g. 2018-06-25
var_dump($sunday->format('Y-m-d')); // e.g. 2018-07-01
Hope this will help.
希望这会有所帮助。