8 版本 Java 如何检查闰年?8 版本 Java 如何获取当前时间戳?
Java 的 java.time 软件包提供日期、时间、实例和持续时间 API。它提供了各种类,例如 Clock、LocalDate、LocalDateTime、LocalTime、MonthDay、Year、YearMonth 等。与之前的备选方案相比,使用此软件包中的类可以更加简单的方式获得与日期和时间有关的详细信息。
Java.time.LocalDate − 此类表示 ISO-8601 日历系统中不包含时区的日期对象。此类的 now() 方法从系统时钟获取当前日期。
java.time.LocalDate 的 isLeapYear() 方法根据 ISO 前儒略日历系统规则验证当前对象中的年份是否是闰年,如果是,则返回 true,否则返回 false。
示例
以下 Java 程序获取当前日期并找出是否是闰年。
import java.time.LocalDate; public class IsLeapYear { public static void main(String args[]) { //Getting the current date LocalDate currentDate = LocalDate.now(); //Verifying if leap year boolean bool = currentDate.isLeapYear(); //is after if(bool){ System.out.println("Current year is a leap year "); }else{ System.out.println("Current year is not a leap year "); } } }
输出
Current year is not a leap year
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
示例
以下示例从用户获取年份,并显示它是否是闰年。
import java.time.LocalDate; import java.util.Scanner; public class IsLeapYear { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the year: "); int year = sc.nextInt(); //Getting the date of jan1st of the given date value LocalDate givenDate = LocalDate.of(year, 01, 01); //Verifying if leap year boolean bool = givenDate.isLeapYear(); //is after if(bool){ System.out.println("Given year is a leap year "); }else{ System.out.println("Given year is not a leap year "); } } }
输出
Enter the year: 2004 Given year is a leap year
广告