Home >Backend Development >PHP Tutorial >How to determine how many days there are in a certain month of a certain year in PHP

How to determine how many days there are in a certain month of a certain year in PHP

小云云
小云云Original
2018-03-20 15:16:101629browse

I recently built a settlement system that needs to automatically perform settlement at the end of the month. Then we must first determine whether that day is the last day of the month. The algorithm is very simple. Posting it is like taking notes yourself. This article mainly shares with you how PHP determines whether a certain day is the last day of the month. How many days are there in a certain month of the year? I hope it can help everyone.

/**
 * 判断某年的某月有多少天
 * @return [type] [description]
 */
function daysInmonth($year='',$month=''){
	if(empty($year)) $year = date('Y');
	if(empty($month)) $month = date('m');
	if (in_array($month, array(1, 3, 5, 7, 8, '01', '03', '05', '07', '08', 10, 12))) {  
            $text = '31';  		 //月大
	}elseif ($month == 2 || $month == '02'){  
		if ( ($year % 400 == 0) || ( ($year % 4 == 0) && ($year % 100 !== 0) ) ) {   //判断是否是闰年  
			$text = '29';        //闰年2月
		} else {  
			$text = '28';  		 //平年2月
		}  
	} else {  
		$text = '30';  			 //月小
	}
	
	return $text;
}

The above is calculated by pure arithmetic, of course there is a simpler method:

/** 
 * 判断某年的某月有多少天 
 * @return [type] [description] 
 */  
function daysInmonth1($year='',$month=''){
	if(empty($year)) $year = date('Y');  
    if(empty($month)) $month = date('m');
	$day = '01';
	
	//检测日期是否合法
	if(!checkdate($month,$day,$year)) return '输入的时间有误';
	
	//获取当年当月第一天的时间戳(时,分,秒,月,日,年)
	$timestamp = mktime(0,0,0,$month,$day,$year);
	$result = date('t',$timestamp);
	return $result;
}

The above is the detailed content of How to determine how many days there are in a certain month of a certain year in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn