2016-02-29 69 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; 
}