php 通过php查找一周的第一天
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4439722/
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
Finding First day of week via php
提问by Future King
Possible Duplicate:
Get first day of week in PHP?
可能的重复:
在 PHP 中获取一周的第一天?
Hi,
你好,
I want to find first and last date of current week and last week. Similarly I want to find first and last date of current month and last month.
我想找到本周和上周的第一个和最后一个日期。同样,我想找到当月和上个月的第一个和最后一个日期。
This has to be done in PHP. Please help.
这必须在 PHP 中完成。请帮忙。
回答by Felix Kling
strtotime
is quite powerful with relative time formats:
strtotime('monday this week');
strtotime('sunday this week');
strtotime('monday last week');
strtotime('sunday last week');
(this only works with PHP 5.3+)
(这只适用于 PHP 5.3+)
strtotime('first day of this month');
strtotime('last day of this month');
strtotime('first day of last month');
strtotime('last day of last month');
In order to get the first and last date of a month in PHP < 5.3, you can use a combination of mktime
and date
(date('t')
gives the number of days of the month):
为了获得在PHP <5.3一个月的第一个和最后一个日期,你可以使用的组合mktime
和date
(date('t')
给出了一个月的天数):
mktime(0,0,0,null, 1); // gives first day of current month
mktime(0,0,0,null, date('t')); // gives last day of current month
$lastMonth = strtotime('last month');
mktime(0,0,0,date('n', $lastMonth), 1); // gives first day of last month
mktime(0,0,0,date('n', $lastMonth), date('t', $lastMonth); // gives last day of last month
If you just want to get a string for presentation, then you don't need mktime
:
如果您只想获取用于演示的字符串,那么您不需要mktime
:
date('Y-m-1'); // first day current month
date('Y-m-t'); // last day current month
date('Y-m-1', strtotime('last month')); // first day last month
date('Y-m-t', strtotime('last month')); // last day last month
回答by prilldev
Here's a function for the first and last day of the week:
这是一周的第一天和最后一天的函数:
function week_start_date($wk_num, $yr, $first = 1, $format = 'F d, Y')
{
$wk_ts = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101'));
$mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts);
return date($format, $mon_ts);
}
$sStartDate = week_start_date($week_number, $year);
$sEndDate = date('F d, Y', strtotime('+6 days', strtotime($sStartDate)));
It can probably be adapted to do month as well, but I wanted to get my answer in! :)
它可能也可以适应做一个月,但我想得到我的答案!:)