显示当前或未来月份的列表日期

时间:2015-02-17 14:41:27

标签: php date strtotime

使用PHP,我希望遍历一个日期列表,只打印适合当前或未来月份的日期。 E.g。

2015年2月
2015年3月
2015年4月

日期格式为“2015年1月15日”。我认为strtotime是最好的方法吗?不知道如何使用它。任何方向都非常感谢。

2 个答案:

答案 0 :(得分:1)

$this_year = date('Y');
$this_month = date('m');    //month in numeric
$year_to_check = date('Y',strtotime($date_to_check));
$month_to_check = date('m',strtotime($date_to_check));

//check if the $this_year is the same or greater than $year_to_check before checking if the months are the same or different

if($year_to_check < $this_year){ //the year is past
   //do not print
 }else if($year == $year_to_check){  //it's either the same year or a future year 
   //check if the month is less
   if($month_to_check < $this_month){
        //the month is past
    }else{
      //the months are the same or $month_to_check is in the future
   }
 }else if($year_to_check > $this_year){
   //the month is in the future because the $year_to_check is in the future
 }

答案 1 :(得分:1)

此功能会将所有日期转换为时间戳并进行比较,以查看您的日期是否介于两者之间。

function checkMyDate($date){
  //set TimeZone
  date_default_timezone_set('GMT');
  //create current timestamp
  $d = new DateTime('now');
  //create timestamp from first of the month
  $d->modify('first day of this month');
  $start = $d->getTimestamp();
  //create timestamp from last day of next month
  $d->modify('last day of next month');
  $end = $d->getTimestamp();
  //convert date to timestamp
  $date = strtotime($date);
  echo $start."-".$end."-".$date;
  //check if $date is between $start and $end
  if($date >= $start && $date <= $end){
    return true;
  }
  return false;
}