java获取年月日

方法一:
该方法已被淘汰,不过可以用

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);//获取一周内的某一天
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值