[英]PHP If given date is date range
我正在嘗試確定給定的日期$my_date
(動態)是否是this week
, last week
, this month
, last month
和last 3 months
$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;
}
什么都沒有顯示。 我該如何解決?
我修改了您的代碼,如果需要進一步修改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;
}
從未定義$dateJob
(if語句的第三和第五個)。
也許您是說$scheduled_job
嗎?
此外,請嘗試以其他方式設置$my_date
格式,因為如果使用/
作為分隔符,則意味着m/d/y
$my_date = "29-02-2016";
只需對str_replace
'/'
str_replace
做'/'
斜杠:
$my_date = str_replace('/', '.', '29/02/2016');
因為strtotime
文檔說:
通過查看各個組成部分之間的分隔符,可以消除m / d / y或dmy格式的日期的歧義:如果分隔符為斜杠(/),則假定為美國m / d / y; 相反,如果分隔符是破折號(-)或點(。),則采用歐洲dmy格式。
我喜歡使用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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.