在Java中获取当前年份的最佳实践是使用java.time包中的LocalDate类或Year类。以下是两种方法:
- 使用LocalDate类获取当前年份:
import java.time.LocalDate; LocalDate currentDate = LocalDate.now(); int year = currentDate.getYear(); System.out.println("Current year: " + year);
- 使用Year类获取当前年份:
import java.time.Year; Year currentYear = Year.now(); int year = currentYear.getValue(); System.out.println("Current year: " + year);
这两种方法都能够获取当前的年份。推荐使用java.time包中的类来处理日期和时间,因为它们提供了更多的功能和更好的性能。