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
示例
以下示例從使用者獲取年份,並顯示它是否是閏年。
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP