技术收藏

关于Java的calendar类

2017-09-30  本文已影响6人  梅斋竹韵

Calendar cale =Calendar.getInstance();

int year = cale.get(Calendar.YEAR);//2017

int month =cale.get(Calendar.MONTH)+1;//9月

int day =cale.get(Calendar.DATE);//30日

int hour =cale.get(Calendar.HOUR);//3时

int hour1 =cale.get(Calendar.HOUR_OF_DAY);//15时

int minute =cale.get(Calendar.MINUTE);//55分

int second =cale.get(Calendar.SECOND);//7秒

int dow =cale.get(Calendar.DAY_OF_WEEK)-1;//这周的周几 --6  (默认周日是1)

int dom =cale.get(Calendar.DAY_OF_MONTH);//30号

int doy =cale.get(Calendar.DAY_OF_YEAR);//今年的多少天-273

int dowm =cale.get(Calendar.DAY_OF_WEEK_IN_MONTH);//这个月的第几周--5

System.out.println(year);

SimpleDateFormat formatter =new SimpleDateFormat("yyyy-MM-dd");

/*获取上一个月第一天*/

cale =Calendar.getInstance();//获取当前日期

cale.add(Calendar.MONTH, -1);

cale.set(Calendar.DAY_OF_MONTH, 1);//设置为1,当前日期就是本月第一天

String firstDay1 = formatter.format(cale.getTime());

System.out.println(firstDay1);//2017-08-01

/*获取上一个月最后一天*/

cale =Calendar.getInstance();

//cale.add(Calendar.MONTH, 1);

cale.set(Calendar.DAY_OF_MONTH, 0);

String lastDay1 =formatter.format(cale.getTime());

System.out.println(lastDay1);//2017-08-31

/*获取本月第一天*/

cale =Calendar.getInstance();//获取当前日期

cale.add(Calendar.MONTH, 0);

cale.set(Calendar.DAY_OF_MONTH, 1);//设置为1,当前日期就是本月第一天

String firstDay = formatter.format(cale.getTime());

System.out.println(firstDay);//2017-09-01

/*获取本月最后一天*/

cale =Calendar.getInstance();

cale.add(Calendar.MONTH, 1);

cale.set(Calendar.DAY_OF_MONTH, 0);

String lastDay =formatter.format(cale.getTime());

System.out.println(lastDay);//2017-09-30

上一篇下一篇

猜你喜欢

热点阅读