方法一:
该方法已被淘汰,不过可以用
String str="2021-8-1";//字符串日期不能直接获取对应方法 格式也可以是2021/08/01,下面的格式必须和这个保持一致
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date date=sdf.parse(str);
date.getYear();//获取年
date.getMonth();//获取月,从0开始
date.getDay();//获取天,从0开始
方法二:
获取现在的年月日
Calendar cal = Calendar.getInstance();
Date date=new Date;//现在的日期
cal.setTime(date);
Integer year=cal.get(Calendar.YEAR);//获取年
Integer month = cal.get(Calendar.MONTH)+1;//获取月(月份从0开始,如果按照中国的习惯,需要加一)
Integer day_moneth=cal.get(Calendar.DAY_OF_MONTH);//获取日(月中的某一天)
Integer day_week=cal.get(Calendar.DAY_OF_WEEK);//获取一周内的某一天
获取指定日期的年月日
String str_date="2020-01-03";
//将字符串转化为日期格式
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(str_date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Integer year=cal.get(Calendar.YEAR);//获取年
Integer month = cal.get(Calendar.MONTH)+1;//获取月(月份从0开始,如果按照中国的习惯,需要加一)
Integer day_moneth=cal.get(Calendar.DAY_OF_MONTH);//获取日(月中的某一天)
Integer day_week=cal.get(Calendar.DAY_OF_WEEK);//获取一周内的某一天