java 獲取本年本月或前月的第一天和最後一天
阿新 • • 發佈:2019-02-18
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat format2=new SimpleDateFormat("yyyy-MM-dd");
//獲取前月的第一天
Calendar cal_1=Calendar.getInstance();//獲取當前日期
cal_1.add(Calendar.MONTH, -1);
cal_1.set(Calendar.DAY_OF_MONTH,1);//設定為1號,當前日期既為本月第一天
firstDay = format.format(cal_1.getTime());
System.out.println("-----1------firstDay:"+firstDay);
//獲取前月的最後一天Calendar cale = Calendar.getInstance();
cale.set(Calendar.DAY_OF_MONTH,0);//設定為0號,當前日期既為前月最後一天,-1即為前月倒數第二天,依次類推
lastDay = format.format(cale.getTime());
System.out.println("-----2------lastDay:"+lastDay);
//獲取當前月第一天:
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 0);
c.set(Calendar.DAY_OF_MONTH,1);//設定為1號,當前日期既為本月第一天
String first = format.format(c.getTime());
System.out.println("===============first:"+first);
//獲取當前月最後一天
Calendar ca = Calendar.getInstance();
ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
String last = format.format(ca.getTime());
System.out.println("===============last:"+last);
//其他
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 0);
c.set(Calendar.DAY_OF_MONTH,1);//設定為1號,當前日期既為本月第一天
int year=c.get(Calendar.YEAR);//獲取本年
String yearFirst=year+"-01";//獲取本年第一月
String first = format.format(c.getTime());//獲取當前月第一天:
String month=format2.format(c.getTime());//獲取當前月