how to get particular date with php

大憨熊 提交于 2021-01-28 14:38:16

问题


I want dates like current week dates from Monday to Wednesday and last week dates from last week Monday to last week Wednesday

I have tried this code

function last_to_last_week_date(){
    $previous_week = strtotime("-2 week +1 day");

    $start_week = strtotime("last monday",$previous_week);
    $end_week = strtotime("next sunday",$start_week);

    $start_week = date("Y-m-d",$start_week);
    $end_week = date("Y-m-d",$end_week);

    return $start_week.' '.$end_week ;
}
function last_week_date(){
    $previous_week = strtotime("-1 week +1 day");

    $start_week = strtotime("last monday",$previous_week);
    $end_week = strtotime("next sunday",$start_week);

    $start_week = date("Y-m-d",$start_week);
    $end_week = date("Y-m-d",$end_week);

    return $start_week.' '.$end_week ;
}

but with this, I have received last week dates and last to last week dates

can anybody help me with this


回答1:


You can simply fix 2 rows in your code:

$end_week = strtotime("next wednesday",$start_week);  // <-- "next wednesday"

And for the current dates:

$previous_week = strtotime("+1 day");    

Demo

Output:

2020-01-20 2020-01-22
2020-01-27 2020-01-29

DRY

You can simplify your code. Use one method in each of two:

function optimDate($prev_w){

    $start_week = strtotime("last monday",$prev_w);
    $end_week = strtotime("next wednesday",$start_week);

    $start_week = date("Y-m-d",$start_week);
    $end_week = date("Y-m-d",$end_week);

    return $start_week.' '.$end_week ;
}

And these two method become like

function last_week_date(){ 
    return optimDate(strtotime("-1 week +1 day"));
}
function curr_week_date(){ 
    return optimDate(strtotime("+1 days"));
}

Demo

In fact, this also could be optimized.



来源:https://stackoverflow.com/questions/59962041/how-to-get-particular-date-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!