在Java中,使用java.time
包中的LocalDate
和DateTimeFormatter
類可以輕松處理閏年。以下是一個簡單的示例,說明如何使用這些類來處理閏年:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
public class LeapYearExample {
public static void main(String[] args) {
// 獲取當前日期
LocalDate currentDate = LocalDate.now();
System.out.println("Current date: " + currentDate);
// 判斷是否為閏年
int year = currentDate.getYear();
boolean isLeapYear = isLeapYear(year);
System.out.println("Is the year " + year + " a leap year? " + isLeapYear);
// 格式化日期
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDate = currentDate.format(formatter);
System.out.println("Formatted date: " + formattedDate);
}
// 判斷是否為閏年的方法
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
}
在這個示例中,我們首先獲取當前日期,然后使用isLeapYear
方法判斷當前年份是否為閏年。接下來,我們使用DateTimeFormatter
類將日期格式化為指定的字符串格式。
isLeapYear
方法的實現基于閏年的定義:如果一個年份能被4整除但不能被100整除,或者能被400整除,那么這個年份就是閏年。