Home > Backend Development > PHP Problem > How to determine whether a year is a leap year in PHP?

How to determine whether a year is a leap year in PHP?

青灯夜游
Release: 2023-02-26 13:46:01
Original
8888 people have browsed it

The condition to determine whether it is a leap year is to meet one of the following two conditions: the year number can be evenly divisible by 4, but not 100; second, the year number can be evenly divisible by 4, but also divisible by 400. So how does PHP determine whether a year is a leap year? The following article will introduce to you how to use PHP to determine whether a year is a leap year. I hope it will be helpful to you.

How to determine whether a year is a leap year in PHP?

1, PHP leap year calculation method 1:

①. Ordinary years can be divisible by 4 but not 100 Divisible by leap years. (For example, 2004 is a leap year, and 1900 is not a leap year)

②. A leap year is a century year that is divisible by 400 but not divisible by 3200. (For example, the year 2000 is a leap year, and the year 3200 is not a leap year)

<?php
header("content-type:text/html;charset=utf-8");
$year=mt_rand(1900,2200);//从1900年到2200,可以自己改,也可以给一个定值。
if($year%100==0){//判断世纪年
if ($year%400==0&&$year%3200!=0){
   echo "世纪年".$year."是闰年!";//世纪年里的闰年
}
else{echo "世纪年".$year."不是闰年!";}
}
else{//剩下的就是普通年了
   if($year%4==0&&$year%100!=0){
   echo "普通年".$year."是闰年!";//普通年里的闰年
}
else {echo "普通年".$year."不是闰年!";}
}
?>
Copy after login

2. Method 2 of judging leap year in php:

<?php
header("content-type:text/html;charset=utf-8");
$year = 2008;//可以像上例一样用mt_rand随机取一个年,也可以随便赋值。
$time = mktime(20,20,20,4,20,$year);//取得一个日期的 Unix 时间戳;
if (date("L",$time)==1){ //格式化时间,并且判断是不是闰年,后面的等于一也可以省略;
echo $year."是闰年";
}else{
echo $year."不是闰年";
}
?>
Copy after login

Method 3 of php judging leap year and calculating leap year:

<?php
header("content-type:text/html;charset=utf-8");
$year = 2000;
$time = mktime(20,20,20,2,1,$year);//取得一个日期的 Unix 时间戳;
if (date("t",$time)==29){ //格式化时间,并且判断2月是否是29天;
echo $year."是闰年";//是29天就输出时闰年;
}else{
echo $year."不是闰年";
}
?>
Copy after login

For more PHP related knowledge, please visit PHP中文网!

The above is the detailed content of How to determine whether a year is a leap year in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template