2016-02-29 76 views
1

我想,以确定是否给定的日期$my_date(动态)是正在显示this weeklast weekthis monthlast monthlast 3 monthsPHP如果给定的日期是日期范围

$my_date = "29/02/2016"; 
$scheduled_job = strtotime($my_date); 
$this_week = strtotime("first day this week"); 
$last_week = strtotime("last week monday"); 
$this_month = strtotime("first day this month"); 
$last_month = strtotime("first day last month"); 
$last_three_month = strtotime("first day -3 month"); 

if($scheduled_job > $this_week) { 
    echo 1; 
} 

if($scheduled_job < $this_week and $scheduled_job >= $last_week) { 
    echo 2; 
} 

if(strtotime($date_job) > $this_month) { 
    echo 3; 
} 

if($scheduled_job < $this_month and $scheduled_job >= $last_month) { 
    echo 4; 
} 

if(strtotime($date_job) > $last_three_month) { 
    echo 5; 
} 

没有。我如何解决?

+0

你有错误在$ my_date中,正确的格式为'$ my_date =“29-02-2016”;' –

+0

如果日期范围不重叠,则可以使用'elseif'。 –

回答

1

$dateJob从未定义(第三和第五条语句)。

也许你的意思是$scheduled_job

此外,尝试以不同的方式来格式化$my_date因为如果使用/作为分隔符,这意味着m/d/y

$my_date = "29-02-2016"; 
1

根本就str_replace'/'斜线:

$my_date = str_replace('/', '.', '29/02/2016'); 

因为strtotime文件说, :

通过查看 各分量之间的分隔符,可以对m/d/y或d-m-y格式的日期进行消歧:如果分隔符是 斜杠(/),则假定为美国m/d/y;而如果 分隔符是破折号( - )或点(。),则假定欧洲的d-m-y格式为 。

1

我pref使用DateTime类。

$date = new \DateTime(); 

$thisMonday = $date->modify('first day of this week'); // to get the current week's first date 
$lastMonday = $date->modify('last monday'); // to get last monday 
$firstDayThisMonth = $date->modify('first day of this month'); // to get first day of this month 
$firstDayLastMonth = $date->modify('first day of this month'); // to get first day of last month 
$firstDayThreeMonthAgo = new \DateTime($firstDayThisMonth->format('Y-m-d') . ' - 3 months'); // first day 3 months ago 

$my_date = str_replace('/', '.', "29/02/2016"); 
$scheduled_job = new \DateTime($my_date); 

// Now you can do the checks. 
2

我修改你的代码,如果需要进一步修改你的if语句,但迄今为止创作的作品如预期,你得到的DateTime对象,你可以做任何你从他们喜欢:

$my_date = "29/02/2016"; 

//this week,last week, this month, last month and last 3 months 
$scheduled_job = DateTime::createFromFormat('d/m/Y', $my_date); 

//test your date 
//echo $scheduled_job->format('Y-m-d'); 

$this_week = new DateTime(date('Y-m-d',strtotime("first day this week"))); 
$last_week = new DateTime(date('Y-m-d',strtotime("last week monday"))); 
$this_month = new DateTime(date('Y-m-d',strtotime("first day this month"))); 
$last_month = new DateTime(date('Y-m-d',strtotime("first day last month"))); 
$last_three_month = new DateTime(date('Y-m-d',strtotime("first day -3 month"))); 


if($scheduled_job > $this_week) { 
    echo 1; 
} 

if($scheduled_job < $this_week and $scheduled_job >= $last_week) { 
    echo 2; 
} 

if($scheduled_job > $this_month) { 
    echo 3; 
} 

if($scheduled_job < $this_month and $scheduled_job >= $last_month) { 
    echo 4; 
} 

if($scheduled_job > $last_three_month) { 
    echo 5; 
}