package com.test.packager; 2 3 import java.text.ParseException; 4 import java.text.SimpleDateFormat; 5 import java.util.Calendar; 6 7 public class Test { 8 private static String firstDay; 9 private static String lastDay; 10 public static void main(String[] args) { 11 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 12 13 //獲取前月的第一天 14 Calendar cal_1=Calendar.getInstance();//獲取當前日期 15 cal_1.add(Calendar.MONTH, -1); 16 cal_1.set(Calendar.DAY_OF_MONTH,1);//設置爲1號,當前日期既爲本月第一天 17 firstDay = format.format(cal_1.getTime()); 18 System.out.println("-----1------firstDay:"+firstDay); 19 //獲取前月的最後一天 20 Calendar cale = Calendar.getInstance(); 21 cale.set(Calendar.DAY_OF_MONTH,0);//設置爲1號,當前日期既爲本月第一天 22 lastDay = format.format(cale.getTime()); 23 System.out.println("-----2------lastDay:"+lastDay); 24 25 26 //獲取當前月第一天: 27 Calendar c = Calendar.getInstance(); 28 c.add(Calendar.MONTH, 0); 29 c.set(Calendar.DAY_OF_MONTH,1);//設置爲1號,當前日期既爲本月第一天 30 String first = format.format(c.getTime()); 31 System.out.println("===============first:"+first); 32 33 //獲取當前月最後一天 34 Calendar ca = Calendar.getInstance(); 35 ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH)); 36 String last = format.format(ca.getTime()); 37 System.out.println("===============last:"+last); 38 39 } 40 /** 41 * 字符串的日期格式的計算 42 */ 43 public static int daysBetween(String smdate,String bdate) throws ParseException{ 44 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 45 Calendar cal = Calendar.getInstance(); 46 cal.setTime(sdf.parse(smdate)); 47 long time1 = cal.getTimeInMillis(); 48 cal.setTime(sdf.parse(bdate)); 49 long time2 = cal.getTimeInMillis(); 50 long between_days=(time2-time1)/(1000*3600*24); 51 return Integer.parseInt(String.valueOf(between_days)); 52 } 53 }