要使用Java Calendar類獲取年月日,可以按照以下步驟進行操作:
java.util.Calendar
類:import java.util.Calendar;
Calendar calendar = Calendar.getInstance();
get
方法獲取年、月、日的值:int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // 注意,Calendar類中的月份是從0開始計數(shù)的,所以需要+1
int day = calendar.get(Calendar.DAY_OF_MONTH);
完整示例代碼如下:
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println("年:" + year);
System.out.println("月:" + month);
System.out.println("日:" + day);
}
}
輸出結果為當前日期的年、月、日。