php获取当前日期所在自然周周一周末以及前后自然周始末

php获取当前日期所在自然周周一周末以及前后自然周始末

首先,获取当前时间,date函数,方法较多,展示一种:

$present = date('y-m-d',time());//当前日期

然后获取当前所在自然周周一周末,看了一些网上的代码,一个案例如下:`

$first = 1;//第一天为周一则为1,第一天为周末为0
$w = date("w",strtotime($present)) ? date("w",strtotime($present)) - $first : 6;
//获取本周开始日期,如果$w是0,则表示周日,减去 6 天
$week_start = date('Y-m-d', strtotime("$present-$w"."days"));
//本周结束日期
$week_end = date('Y-m-d', strtotime("$week_start +6 days"));

思路为条件赋值算出需要减去的天数(语法:strtotime("date - 时间单位数量"."时间单位"))来求出所在自然周周一。strtotime函数中days为时间单位,不可缺少。

这种方法语法相对复杂。
都存在days这样的嵌入自然语言单位了,那必定有其他。查阅后果然:

echo(strtotime("last Sunday"));
echo(strtotime("+1 week") . "<br>");
echo(strtotime("now") . "<br>");

既然如此那么本周一和周末就可以表示为:

//本周一
$test_Monday = date('Y-m-d',strtotime("last Sunday+1days"));
//本周末
$test_Sunday = date('Y-m-d',strtotime("next Monday-1days"));

要获得上周的周一和周末,我们可以再大胆一点:

$last_week_start = date('Y-m-d', strtotime('last week monday'));
$last_week_end = date('Y-m-d', strtotime('last week sunday'));

还要什么当前时间算什么当前周几啊,GPT赶紧引进吧!

Tips:

  1. strtotime周五查周五,前(last)后(next)差7天;
  2. 前一个月后一个月以此类推。
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值