從數據庫或前端獲取日期對象,需只保留年份,或單獨提取月、日,不知如何高效處理。
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
LocalDate date = LocalDate.now(); // 或 LocalDate.parse("2023-05-20")
int year = date.getYear(); // 2023
int month = date.getMonthValue(); // 5
int day = date.getDayOfMonth(); // 20
// 只輸出年份字符串
String yearStr = date.format(DateTimeFormatter.ofPattern("yyyy")); // "2023"
// 從 LocalDateTime
LocalDateTime ldt = LocalDateTime.now();
int year2 = ldt.getYear();
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.Date;
Date date = new Date(); // 或從數據庫獲取
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1; // 月份 0-11
int day = cal.get(Calendar.DAY_OF_MONTH);
// 格式化輸出年份
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
String yearStr = sdf.format(date);
若只需年份,直接在 SQL 中提取,減少應用層計算:
SELECT YEAR(create_time) AS yr FROM tableSELECT EXTRACT(YEAR FROM create_time) FROM tableSELECT YEAR(create_time) FROM tableSELECT EXTRACT(YEAR FROM create_time) FROM tablejava.time 包,線程安全、API 清晰。