Php 检查日期是否比当前日期旧或新(按月)
我想检查给定的日期(如2012-12)是否比当前日期旧或新 我知道如何检查旧的月份,比如Php 检查日期是否比当前日期旧或新(按月),php,date,if-statement,Php,Date,If Statement,我想检查给定的日期(如2012-12)是否比当前日期旧或新 我知道如何检查旧的月份,比如 if(strtotime('2012-12')<strtotime('-1 Months')){ echo "true"; // got TRUE ... correct! } else { echo "false"; } 我在检查较新的日期时得到了不正确的结果。您忘记将+添加到strotime函数中 if(strtotime('2013-02')>strtotime('+1 M
if(strtotime('2012-12')<strtotime('-1 Months')){
echo "true"; // got TRUE ... correct!
} else {
echo "false";
}
我在检查较新的日期时得到了不正确的结果。您忘记将+添加到strotime函数中
if(strtotime('2013-02')>strtotime('+1 Months')){
echo "true";
} else {
echo "false";
}
更新:
你的问题有些奇怪。例如,2013-02不是日期,而是对月份的引用。如果您想检查这是否是一个月的第一天,请使用完整日期符号:2012-02-01。如果要检查当前日期是否为月份,请使用日期(“n”)
检查当前月份(返回1-12);并将其与给定月份进行比较,例如:
$date = "2012/02/01";
if(date("n", strtotime($date)) != date("n")) {
echo 'not current month';
}
如果要检查这是否不是当前日期,请执行以下操作:
$date = "2012/02/01";
if(date('d-m-Y', strtotime($date)) != date('d-m-Y')) {
echo 'not current day';
}
如果您想将日期与当前时间进行比较,看看它是在过去还是在未来,您可以使用
$date = '2013-02';
$now = time();
if ( strtotime($date) > $now ) {
echo 'Date is in the future';
} else {
echo 'Date is in the past';
}
但是请注意,如果您提供的日期类似于
$date='2013-01'
,即没有日期,则它将返回过去的日期,即使我们仍在1月份。请务必查看这是否是您想要的行为比较字符串如何?如果您可以使用ISO 8601格式yyyy mm dd直接比较字符串,那么它们总是按字典顺序排列的
2012-01<2012-122013-01<2013-02<2014-01
(加粗的是当前时间)如果要与“现在”进行比较,为什么要使用1个月前的时间或1个月后的时间?是否可以扩展@Pankratesif给出当前日期,结果是“过去”,这正是我提到的原因,你会把今天当作未来吗?如果您没有指定确切的日期和时间,您如何区分它是在过去还是将来。如果你想要一个更详细的答案,你需要澄清确切的功能,你正在寻找我会使用这个技巧,但我不能接受你的答案。我希望你能理解:D
$date = '2013-02';
$now = time();
if ( strtotime($date) > $now ) {
echo 'Date is in the future';
} else {
echo 'Date is in the past';
}