首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果给定日期是日期范围,则为PHP

如果给定日期是日期范围,则为PHP
EN

Stack Overflow用户
提问于 2016-02-29 21:47:07
回答 4查看 94关注 0票数 1

我正在尝试确定给定的日期$my_date(动态)是否为this weeklast weekthis monthlast monthlast 3 months

代码语言:javascript
复制
$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;
} 

未显示任何内容。我该如何解决?

EN

回答 4

Stack Overflow用户

发布于 2016-02-29 22:21:54

我修改了你的代码,如果需要进一步修改if语句,但日期创建工作如预期,你得到DateTime对象,你可以从它们做任何你喜欢的事情:

代码语言:javascript
复制
$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;
}
票数 2
EN

Stack Overflow用户

发布于 2016-02-29 22:00:22

从未定义过$dateJob (第三个和第五个if语句)。

也许你指的是$scheduled_job

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

代码语言:javascript
复制
$my_date = "29-02-2016";
票数 1
EN

Stack Overflow用户

发布于 2016-02-29 22:00:38

只需对'/'斜杠执行str_replace

代码语言:javascript
复制
$my_date = str_replace('/', '.', '29/02/2016');

因为strtotime文档说:

通过查看各个组件之间的分隔符,可以消除m/d/y或d-m-y格式的

日期的歧义:如果分隔符是斜杠(/),则假定为美国的m/d/y;而如果分隔符是短划线(-)或点(.),则假定为欧洲的d-m-y格式。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35701218

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档